/// <summary> /// Use heaps to find a running median in an array of integers. /// </summary> /// <param name="input"></param> /// <returns></returns> public static double FindMedian(int[] input) { MaxHeap lowerHalfHeap = new MaxHeap(input.Length / 2); Heap upperHalfHeap = new Heap(input.Length / 2); foreach (int item in input) { if (lowerHalfHeap.Size <= upperHalfHeap.Size) { lowerHalfHeap.Add(item); } else { upperHalfHeap.Add(item); } Heap.Balance(lowerHalfHeap, upperHalfHeap); } if (input.Length % 2 == 0) { return((double)(lowerHalfHeap.Peek() + upperHalfHeap.Peek()) / 2); } else { return((double)lowerHalfHeap.Peek()); } }
/// <summary> /// Helper method to balance heaps after each addition. /// </summary> /// <param name="lowerHeap"></param> /// <param name="upperHeap"></param> public static void Balance(MaxHeap lowerHeap, Heap upperHeap) { while (lowerHeap.Size > 0 && upperHeap.Size > 0 && lowerHeap.Peek() > upperHeap.Peek()) { int lowHead = lowerHeap.Poll(); int highHead = upperHeap.Poll(); upperHeap.Add(lowHead); lowerHeap.Add(highHead); } }