Multiple Array Merge Using Binary Heap

陌路散爱 提交于 2019-12-01 06:37:45

Name the k-sorted lists 1, ..., k.

Let A be the name of the combined sorted array.

For each list, i, pop v off of i and push (i, v) into a min-heap. Now the heap will contain pairs of value and list id for the smallest entries in each of the lists.

While the heap is not empty, pop (i, v) from the heap and append v to A. Pop the next item off list i (if it's not empty) and put it in the heap.

There are n additions and removals from the heap. The heap contains at most k elements at every time step. Hence the runtime is O(n log k).

Maybe just that the invariant is that the heap contains the smallest elements from the arrays that haven't been emptied. When you try to pop an item off list i, if this list is empty, you go on popping elements off the heap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!