private static int Partition <T>(T[] arr, int left, int right, Comparator.IComparable <T> comparer) { int i = left, j = right; T tmp; T pivot = arr[(left + right) / 2]; while (i <= j) { while (comparer.Compare(arr[i], pivot) == -1) { i++; } while (comparer.Compare(arr[j], pivot) == 1) { j--; } if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } } return(i); }
public static int DoSearch <T>(T[] array, int left, int right, T x, Comparator.IComparable <T> comparer = null) { // ############################# // check null & type | // ^ ////Type arrayType = A.GetType(); ////arrayType.GetInterface("IComparer"); array.ToSort(0, array.Length - 1, comparer); return(Search(array, left, right, x, comparer)); }
internal static void ToSort <T>(this T[] arr, int left, int right, Comparator.IComparable <T> comparer) { int index = Partition(arr, left, right, comparer); if (left < index - 1) { ToSort(arr, left, index - 1, comparer); ////arr.ToSort(left, index - 1); } if (index < right) { ToSort(arr, index, right, comparer); ////arr.ToSort(index, right); } }
public static int Search <T>(T[] array, int left, int right, T x, Comparator.IComparable <T> comparer) { if (left > right || comparer.Compare(x, array[left]) == -1 /*x < A[left]*/ || comparer.Compare(x, array[left]) == 1 /*x > A[right]*/) { return(-1); } int mid = left + ((right - left) / 2); if (comparer.Compare(x, array[mid]) == 0) { return(mid); } if (comparer.Compare(x, array[left]) == -1) { return(Search(array, left, mid - 1, x, comparer)); } else { return(Search(array, mid + 1, right, x, comparer)); } }