Insert 5 Insert 15 Insert 1 Insert 3 Find median
After inserting 5, 15, 1, 3, the two heaps balance to hold the lower half and upper half of numbers. The median is the average of the two middle numbers: (3 + 5) / 2 = 4.0.
The two heaps split the data stream into lower and upper halves. The max heap stores the smaller half, and the min heap stores the larger half. This allows quick access to the middle values needed for median calculation.
if (maxHeapSize > minHeapSize + 1) { int val = extractMax(maxHeap); insertMin(minHeap, val); } else if (minHeapSize > maxHeapSize) { int val = extractMin(minHeap); insertMax(maxHeap, val); } median = (maxHeapSize == minHeapSize) ? (maxHeap[0] + minHeap[0]) / 2 : maxHeap[0];
The code moves elements between heaps but does not update the heap size variables. This causes incorrect median calculation and possible out-of-bounds errors.
Insert 2 Insert 4 Insert 7 Insert 1 Insert 5 Insert 3 Find median
After inserting all numbers, the two heaps split the data into halves: lower half [1,2,3] and upper half [4,5,7]. Median is average of 3 and 4 = 3.5.
Two heaps allow O(log n) insertion and O(1) median retrieval, making them efficient for large real-time data streams. Sorting after each insertion or traversing trees is slower. Ignoring data loses accuracy.
