public static void Test() { int[] array = { 3, 1, 2, 5, 6, 7, 9, 10, 4, 8}; MaxPQ pq = new MaxPQ(array); for (int i = 0; i < array.Length; i++) Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 Console.WriteLine(); pq = new MaxPQ(2); for (int i = 0; i < array.Length; i++) pq.Insert(array[i]); while (pq.Count() > 0) Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 Console.WriteLine(); }
// use max priority queue of size k // since insert/delete are O(lg k), time complexity O(N lg k) public static int KthSmallest(int[] a, int k) { MaxPQ pq = new MaxPQ(k); for (int i = 0; i < a.Length; i++) { if (i < k) pq.Insert(a[i]); else if (pq.GetMax() > a[i]) { pq.DeleteMax(); pq.Insert(a[i]); } } return pq.GetMax(); }
// use max priority queue of size k // since insert/delete are O(lg k), time complexity O(N lg k) public static int KthSmallest(int[] a, int k) { MaxPQ pq = new MaxPQ(k); for (int i = 0; i < a.Length; i++) { if (i < k) { pq.Insert(a[i]); } else if (pq.GetMax() > a[i]) { pq.DeleteMax(); pq.Insert(a[i]); } } return(pq.GetMax()); }
public static void Test() { int[] array = { 3, 1, 2, 5, 6, 7, 9, 10, 4, 8 }; MaxPQ pq = new MaxPQ(array); for (int i = 0; i < array.Length; i++) { Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 } Console.WriteLine(); pq = new MaxPQ(2); for (int i = 0; i < array.Length; i++) { pq.Insert(array[i]); } while (pq.Count() > 0) { Console.Write(pq.DeleteMax() + " "); // 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 } Console.WriteLine(); }