Two heaps give the middle of a stream
transcript
Scores arrive one at a time. Show the middle score after each. Do not sort every time. Two heaps do it.
Split the scores into two halves. The lower half is a max-heap. The upper half is a min-heap. The two tops are the middle values.
Lower half: five and three. Five is on top. Upper half: eight and twelve. Eight is on top. The cut sits between five and eight. Even count: average five and eight.
Every lower value is at most every upper value. The lower half has the same count, or one more. Odd count: the lower top is the median. Even count: average of both tops.
Each add costs about log n. Reading the median costs one step. A sorted list shifts up to n values. Two heaps stay quick on long streams.
A max-heap below, a min-heap above. The tops are the middle. Try it in the sandbox. Full breakdown in the lecture.