Created
September 21, 2013 02:57
O(nlogk) algorithm for k-way merge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge2(arr): | |
heap = [(l[0],i,0) for i,l in enumerate(arr) if len(l) > 0] | |
heapq.heapify(heap) | |
lst = [] | |
while heap: | |
item,lst_index,item_index = heapq.heappop(heap) | |
lst.append(item) | |
if item_index + 1 < len(arr[lst_index]): | |
heapq.heappush(heap,(arr[lst_index][item_index+1],lst_index,item_index+1)) | |
return lst |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment