Merge sorted lists with a heap of fronts
transcript
Three sorted lists. You want one sorted line. Do not sort them all. Look at the front of each list. A heap does the rest.
Three fronts: one, two and four. They go in a min-heap. Pop the smallest. One goes out. Its list has a new front, five. Push it. Pop again. Two goes out. Push six, the next of that list.
Pop the smallest front. Push the next item of its list. The heap holds one item for each list. That is at most k items.
Each value costs one pop and one push. The heap is small, so each step is quick. Memory is only k entries. Sorting all of it costs n log n.
Take a million values in eight lists. The heap holds eight items. Each pop or push climbs about three levels. A full sort needs about twenty steps for each value. The heap of fronts wins when k is small.
Hold only the front of each list. Pop one, push the next. Try it in the sandbox. Full breakdown in the lecture.