Here's a python implementation for it. I tested some of the examples generated using Random.org and tested them on median finder most of them seem to work.
import heapq
def medianFinder(arr):
minHeap = []
maxHeap = []
def handleMedianFinder(num: int):
if not len(maxHeap):
heapq.heappush(maxHeap, -num)
return -maxHeap[0]
elif not len(minHeap):
heapq.heappush(minHeap, num)
return (minHeap[0]-maxHeap[0])/2
if num < minHeap[0]:
if len(maxHeap) > len(minHeap):
oldMedian = -heapq.heappop(maxHeap)
heapq.heappush(minHeap, oldMedian)
heapq.heappush(maxHeap, -num)
return (minHeap[0]-maxHeap[0])/2 if (len(minHeap) + len(maxHeap))%2 == 0 else minHeap[0]
heapq.heappush(maxHeap, -num)
elif num > -maxHeap[0]:
if len(maxHeap) < len(minHeap):
oldMedian = heapq.heappop(minHeap)
heapq.heappush(maxHeap, -oldMedian)
heapq.heappush(minHeap, num)
return (minHeap[0]-maxHeap[0])/2 if (len(minHeap) + len(maxHeap))%2 == 0 else -maxHeap[0]
heapq.heappush(minHeap, num)
else: # between the medians (new medians)
if len(maxHeap) < len(minHeap):
oldMedian = heapq.heappop(minHeap)
heapq.heappush(maxHeap, -oldMedian)
heapq.heappush(minHeap, num)
else:
oldMedian = -heapq.heappop(maxHeap)
heapq.heappush(minHeap, oldMedian)
heapq.heappush(maxHeap, -num)
if len(minHeap) < len(maxHeap):
return minHeap[0]
elif len(maxHeap) < len(minHeap):
return -maxHeap[0]
return (minHeap[0]-maxHeap[0])/2
for num in arr:
# print('maxHeap => ', maxHeap)
# print('minHeap => ', minHeap)
print(handleMedianFinder(num))
arr1 = [11, 18, 16, 12, 14, 4, 15, 10, 19, 20]
medianFinder(arr1)