Skip to content

Instantly share code, notes, and snippets.

@st0le
Created September 21, 2013 02:57
O(nlogk) algorithm for k-way merge
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