Given s lists of n elements each, sorted in descending order, we want to produce a sorted list that will contain top n items from the input lists, combined. The trivial algorithm is:
- Take the first item from every list
- Pick the largest item from these. Remove it from its input list, and output it
- Repeat the above steps until we output n elements
However, given that the list of items in point 2 is almost identical every time (only 1 item changes between iterations), we can achieve much better results using a heap-based priority queue. Updated algorithm:
- Take the first item from every list, build a priority queue
- Pick and remove the largest item from the queue. Output the item.
- Add next item from the same list to the queue.
- Repeat steps 2 and 3 until we output n elements
Now, knowing how the priority queues are implemented, we can save one operation by replacing the top element in queue instead of removing + adding. This way we rebuild heap only once.
Note: in rare cases this could result in doing more operations instead of less.
Sample implementation in C++
No comments:
Post a Comment