/// <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(); } }
/// <summary> /// Null cannot be added to the queue at all. /// </summary> public void TestBinaryHeapException() { IPriorityQ <string> q = new SimpleBinaryHeap <string>(); TestDelegate stuff = () => { q.Enqueue(null); }; AssertThrow <InvalidArgumentException>(stuff); TestDelegate stuff2 = () => { q.RemoveMin(); }; AssertThrow <InvalidOperationException>(stuff2); }
public void BinaryHeapBasic(int size, int repetition) { for (int j = 1; j <= repetition; j++) { IPriorityQ <int> q = new SimpleBinaryHeap <int>(); int[] randomarr = GetRandomizedIntSequence(size); for (int i = 0; i < randomarr.Length; q.Enqueue(randomarr[i]), i++) { ; } for (int i = 0; i < randomarr.Length; Assert.AreEqual(i + 1, q.RemoveMin()), i++) { ; } } }