/// <summary> /// Rearranges the array so that a[k]} contains the kth smallest key; /// a[0] through a[k-1] are less than (or equal to) a[k]; /// a[k+1] through a[n-1] are greater than (or equal to) a[k]. /// </summary> /// <param name="a">the array</param> /// <param name="k">the rank of the key</param> /// <returns>the key of rank k}</returns> public static T Select(T[] a, int k) { if (k < 0 || k >= a.Length) { throw new ArgumentOutOfRangeException(nameof(k), k, "out of bounds"); } StdRandom.shuffle(a); int lo = 0, hi = a.Length - 1; while (hi > lo) { int i = partition(a, lo, hi); if (i > k) { hi = i - 1; } else if (i < k) { lo = i + 1; } else { return(a[i]); } } return(a[lo]); }
/// <summary> /// Rearranges the array in ascending order, using the natural order. /// </summary> /// <param name="a">the array to be sorted</param> public static void Sort(T[] a) { StdRandom.shuffle(a); sort(a, 0, a.Length - 1); Debug.Assert(SortingHelper <T> .isSorted(a)); }