/// <summary> /// Sort the top K element from an array, using floyd build heap. /// it will not modify the input. /// <remark> /// Complexity expected to be: /// O(k+(n-k)Log(k)) => O(nlog(k)) /// </remark> /// </summary> /// <param name="len"></param> /// <param name="k"></param> /// <returns></returns> public static T[] TopKSortDoubleArrayUsingBinaryHeap <T>(T[] arr, int k) where T : IComparable <T> { if (k <= 0 || arr == null || arr.Length == 0) { return(null); } k = k >= arr.Length ? arr.Length : k; IPriorityQ <T> q = new SimpleBinaryHeap <T>(arr, 0, k); for (int i = k; i < arr.Length; i++) { T element = arr[i]; if (element.CompareTo(q.Peek()) > 0) { q.RemoveMin(); q.Enqueue(element); } } T[] res = new T[k]; for (int i = 0; i < k; i++) { res[i] = q.RemoveMin(); } return(res); }
public void TestPartialFloydBuildHeap() { int[] randomarr = GetRandomizedIntSequence(100); IPriorityQ <int> q = new SimpleBinaryHeap <int>(randomarr, 90, 9); int pre = q.RemoveMin(); while (q.Size != 0) { Assert.IsTrue(q.Peek() > pre); pre = q.RemoveMin(); } }