46 lines
942 B
Python
46 lines
942 B
Python
from collections import deque
|
|
|
|
|
|
|
|
def mergesort(iterable):
|
|
if(len(iterable) == 1):
|
|
return iterable
|
|
|
|
mid = len(iterable) // 2
|
|
left = mergesort(iterable[:mid])
|
|
right = mergesort(iterable[mid:])
|
|
|
|
result = deque()
|
|
while(left or right):
|
|
if(left):
|
|
cmp_left = left[0]
|
|
else:
|
|
cmp_left = None
|
|
if(right):
|
|
cmp_right = right[0]
|
|
else:
|
|
cmp_right = None
|
|
|
|
if(cmp_left != None
|
|
and cmp_right != None):
|
|
if(cmp_left < cmp_right):
|
|
result.append(left.pop(0))
|
|
else:
|
|
result.append(right.pop(0))
|
|
continue
|
|
if(cmp_left != None):
|
|
result.append(left.pop(0))
|
|
continue
|
|
if(cmp_right != None):
|
|
result.append(right.pop(0))
|
|
continue
|
|
return list(result)
|
|
|
|
if( __name__ == "__main__"):
|
|
|
|
test_data = [0, 1, 4, 5, 2, 9, 12, 3]
|
|
|
|
assert mergesort(test_data) == list(sorted(test_data))
|
|
print(mergesort([ 5 , 4 , 21 , 11 , 1 , 17 , 20 , 2 , 3 , 7 , 8 , 22 , 6 ,
|
|
10 , 13 , 14 , 18 , 15 , 16 , 19 , 12 , 9 , 0 ]))
|