public void AddNum(int num) //Always trying to keep maxheap.Count>=minheap.Count { if (maxheap.Count == 0) { maxheap.Insert(num); } else if (maxheap.Count > minheap.Count) { if (num >= maxheap.Max) //it belongs to minheap, and there is enough space { minheap.Insert(num); } else //it belongs to maxheap, but there is no enough space { minheap.Insert(maxheap.ExtractMax()); maxheap.Insert(num); } } else if (maxheap.Count == minheap.Count) { if (num >= maxheap.Max) //it belongs to minheap, but there is no enough space { maxheap.Insert(minheap.ExtractMin()); minheap.Insert(num); } else //it belongs to maxheap and there is enough space { maxheap.Insert(num); } } }
/////////////////////Heap Sort//////////////////////////// public static void HeapSort(T[] array) { MinHeap <T> minheap = new MinHeap <T>(); for (int i = 0; i < array.Length; i++) { minheap.Insert(array[i]); } for (int i = 0; i < array.Length; i++) { array[i] = minheap.ExtractMin(); } }