The kth smallest, by stopping early
transcript
A grid of prices. Rows and columns are sorted. You want the fifth smallest. Do not sort the grid. Merge, and stop early.
The row fronts are one, two and six. Pop one. Push three, the next in its row. Pop two. Push four. Pop three, then four. Push five and eight. Four are out. The top is the fifth smallest.
You pop k times and stop. The cost is about k log k. The grid could hold millions of prices. It makes no difference.
Columns never fall. A lower row starts no lower than the row above. So k values come out before it. Start the heap with only k rows.
The grid is one, three, five. Two, four, eight. Six, seven, nine. Each row is a sorted list. Only the first values of each row go in the heap. The rest is worked out as you go.
Merge the rows with a heap. Stop after k pops. The top is the kth smallest. Full breakdown in the lecture.