Give an O(n log k) time algorithm to merge k sorted lists into one sorted list,
ID: 3638909 • Letter: G
Question
Give an O(n log k) time algorithm to merge k sorted lists into one sorted list, where n is the total number of elements in all the input lists.
Please check answer below what corrections needs to be done? or what do you propose?
Potential answer:
Given k sorted lists with a total of n elements show how to merge them in O(n lg k) time. Insertall k elements a position 1 from each list into a heap. Use EXTRACT-MAX to obtain the rst elementof the merged list. Insert element at position 2 from the list where the largest element originallycame from into the heap. Continuing in this fashion yields the desired algorithm. Clearly therunning time is O(n lg k).
Explanation / Answer
First we remove the smallest element from each sorted listand we build a min-priority queue (using a min-heap) out of theseelements in O(k) time. Then we repeat the following steps: we extractthe minimum from the min-priority queue (in O(log k) time) and thiswill be the next element in the sorted order. From the original sortedlist where this element came from we remove the next smallest element(if it exists) and insert it to the min-priority queue (in O(log k) time).We are done when the queue becomes empty and at this point wehave all the numbers in our sorted list. The total running time isO(k + n log k) = O(n log k).
This is the best answer to my knowledge.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.