public T[] Sort <T>(T[] input) where T : IComparable { for (int i = 0; i < input.Length - 1; i++) { int jMin = i; for (int j = i + 1; j < input.Length; j++) { if (input[j].CompareTo(input[jMin]) < 0) { jMin = j; } } SortingUtils.Swap(input, i, jMin); } return(input); }
private int Partition <T>(T[] input, int low, int high) where T : IComparable { T pivot = input[high]; int i = low; for (int j = low; j < high; j++) { if (input[j].CompareTo(pivot) < 0) { SortingUtils.Swap(input, i, j); i++; } } SortingUtils.Swap(input, i, high); return(i); }
public async Task <T[]> SortParallel <T>(T[] input) where T : IComparable { if (input.Length <= 1) { return(input); } int middle = input.Length / 2; T[] inputA = SortingUtils.Take(input, 0, middle); T[] inputB = SortingUtils.Take(input, middle, input.Length); Task tA = Task.Run(() => Sort(inputA)); Task tB = Task.Run(() => Sort(inputB)); await Task.WhenAll(tA, tB); int iA = 0, iB = 0; for (int i = 0; i < input.Length; i++) { if (iA == inputA.Length) { input[i] = inputB[iB]; iB++; } else if (iB == inputB.Length) { input[i] = inputA[iA]; iA++; } else if (inputA[iA].CompareTo(inputB[iB]) < 0) { input[i] = inputA[iA]; iA++; } else { input[i] = inputB[iB]; iB++; } } return(input); }
public T[] Sort <T>(T[] input) where T : IComparable { if (input.Length <= 1) { return(input); } int middle = input.Length / 2; T[] inputA = SortingUtils.Take(input, 0, middle); T[] inputB = SortingUtils.Take(input, middle, input.Length); Sort(inputA); Sort(inputB); int iA = 0, iB = 0; for (int i = 0; i < input.Length; i++) { if (iA == inputA.Length) { input[i] = inputB[iB]; iB++; } else if (iB == inputB.Length) { input[i] = inputA[iA]; iA++; } else if (inputA[iA].CompareTo(inputB[iB]) < 0) { input[i] = inputA[iA]; iA++; } else { input[i] = inputB[iB]; iB++; } } return(input); }