Last active
August 29, 2015 14:13
-
-
Save jpoler/8dac0e25feff87e24864 to your computer and use it in GitHub Desktop.
K-way merge sort
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
from heapq import heappush, heappop | |
class StreamScore(object): | |
def __init__(self, stream, key, value): | |
self.stream = stream | |
self.key = key | |
self.value = value | |
def __lt__(self, other): | |
if self.key == other.key: | |
return self.value < other.value | |
return self.key < other.key | |
def __le__(self, other): | |
if self.key == other.key: | |
return self.value <= other.value | |
return self.key <= other.key | |
def __eq__(self, other): | |
return self.key == other.key | |
def __ne__(self, other): | |
return self.key != other.key | |
def __gt__(self, other): | |
if self.key == other.key: | |
return self.value > other.value | |
return self.key > other.key | |
def __ge__(self, other): | |
if self.key == other.key: | |
return self.value >= other.value | |
return self.key >= other.key | |
def k_way_merge(streams): | |
sorted = [] | |
heap = [] | |
empty = [False]*len(streams) | |
for i in range(len(streams)): | |
if len(streams[i]) != 0: | |
key, value = streams[i].pop(0) | |
heappush(heap, StreamScore(i, key, value)) | |
while (not all(empty)): | |
next = heappop(heap) | |
sorted.append((next.key, next.value)) | |
if len(streams[next.stream]) == 0: | |
empty[next.stream] = True | |
else: | |
key, value = streams[next.stream].pop(0) | |
heappush(heap, StreamScore(next.stream, key, value)) | |
print(len(heap)) | |
return sorted | |
test = [ | |
[(2,100), (5, 200), (1, 50), (2, 200), (7, 1)], | |
[(18, 50), (4, 66), (90, 1), (20, 300)], | |
[(78, 3), (3, 78), (10, 2), (2, 100)] | |
] | |
sorted_test = [sorted(i) for i in test] | |
print(k_way_merge(sorted_test)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment