Created
June 4, 2017 13:20
-
-
Save Eitol/7046d25c07c7e871a3028c0d99cf2ff3 to your computer and use it in GitHub Desktop.
Merge sort using queues made in python3
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 collections import deque | |
def merge_sort(v: list) -> list: | |
if len(v) < 2: | |
return v | |
middle = int(len(v) / 2) | |
left = deque(merge_sort(v[:middle])) | |
right = deque(merge_sort(v[middle:])) | |
out = [] | |
while left and right: | |
out += [left.popleft()] if left[0] < right[0] else [right.popleft()] | |
out += left or right | |
return out | |
# Test 1 | |
v_t1 = [7, 5, 9, 3, 1, 6] | |
print(merge_sort(v_t1)) | |
# Test 2 | |
v_t1 = [1, 7, 5, 9, 3, 1, 6] | |
print(merge_sort(v_t1)) | |
# Test 3 | |
v_t1 = [] | |
print(merge_sort(v_t1)) | |
# Test 4 | |
v_t1 = ['z', 'a', 'f', '<', 'c', '*'] | |
print(merge_sort(v_t1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment