Merging K- Sorted Lists using Priority Queue

后端 未结 7 1549
无人及你
无人及你 2021-01-06 18:17

I have been asked in my algorithm class to make a K-way merge algorithm which is of O(nlogk) After searching i found it could be done via making a k length prio

7条回答
  •  走了就别回头了
    2021-01-06 18:29

    Instead of simply storing the first element of each list in the priority queue, wrap it in a structure like this;

    struct wrapper
    {
        int list_number;
        int element;
    }
    

    Then, when you are pushing an element onto the priority queue, just add the list number form where it came. This way, when the minimum element gets popped, you will know from which list you should push the next element to push on the queue by examining popped_element.list_number.

    In order to find if your list is empty you should add a function empty to it that returns true if the list does not have any more elements and false otherwise. The function would be very easy to implement. Just check if the size is zero then the list is empty otherwise it has one or more elements.

    From your question I assume that a binary heap is used to implement the priority queue. The insertion operation in a binary heap takes O(lg k) time and the extract-min operation also takes O(lg k) times where k is the the size of the heap (number of lists in your case). Now if the total number of elements you have is n, the total time to process all of them will be O(n lg k).

提交回复
热议问题