Why the worst is on top
transcript
A stream never stops. You need the three largest values. Sorting every time is slow. Sorting a hundred thousand values again and again wastes work. Keep a heap of size three instead.
The heap holds the best three so far. The worst of them sits on top. So you only compare with one value. A new value must beat that top. If it does, it replaces the top.
Sometimes two items tie. Put the tie rule in the key, such as the smaller id. Then the heap never has to guess.
The first three fill the heap. Seven beats the top, two. It enters. The next seven beats four. It enters. Five is too small. It is ignored. Ten beats seven, so it enters. The heap holds seven, nine, ten.
Most values cost one comparison. A replacement costs about log k steps. Memory stays at k items.
Keep the best k. Worst on top. Beat the top to enter. Full breakdown in the lecture.