Insert 5 Insert 15 Insert 1 Insert 3 Find median
After inserting 5 and 15, the median is (5 + 15)/2 = 10. After inserting 1, median is 5. After inserting 3, the two heaps are balanced and the median is (3 + 5)/2 = 4.0.
Two heaps split the data into lower and upper halves. Max-heap stores the smaller half, min-heap stores the larger half. Balancing them keeps insertion O(log n) and median retrieval O(1).
if (maxHeap.Count == 0 || num <= maxHeap.Peek()) maxHeap.Add(num); else minHeap.Add(num); if (maxHeap.Count > minHeap.Count + 1) minHeap.Add(maxHeap.ExtractMax()); else if (minHeap.Count > maxHeap.Count) maxHeap.Add(minHeap.ExtractMin()); return (maxHeap.Count == minHeap.Count) ? (maxHeap.Peek() + minHeap.Peek()) / 2 : maxHeap.Peek();
In C#, dividing two integers performs integer division, truncating decimals. So when counts are equal, the median calculation (maxHeap.Peek() + minHeap.Peek()) / 2 returns an integer, losing the decimal part.
Insert 2 Insert 4 Insert 7 Insert 1 Insert 5 Insert 3 Find median
After all insertions, the two heaps are balanced with equal size. Median is average of max-heap top (3) and min-heap top (4), so (3 + 4)/2 = 3.5.
Insertion into a heap is O(log n) due to reheapifying. Median retrieval is O(1) because it is the top element(s) of the heaps.
