Created
August 28, 2019 08:12
-
-
Save eirenik0/b5c7f33601642d5b6e27343a13472857 to your computer and use it in GitHub Desktop.
Python implementation of merge sort
This file contains hidden or 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 ordered_combine(lhs, rhs): | |
lst = [] | |
l_i = r_i = 0 | |
while l_i < len(lhs) and r_i < len(rhs): | |
if lhs[l_i] < rhs[r_i]: | |
lst.append(lhs[l_i]) | |
l_i += 1 | |
else: | |
lst.append(rhs[r_i]) | |
r_i += 1 | |
lst += lhs[l_i:] | |
lst += rhs[r_i:] | |
return lst | |
def merge_sort(lst): | |
size = len(lst) | |
if size == 1: | |
return lst | |
half = int(size / 2) | |
lhs = lst[:half] | |
rhs = lst[half:] | |
lhs = merge_sort(lhs) | |
rhs = merge_sort(rhs) | |
return ordered_combine(lhs, rhs) | |
assert merge_sort([5, 2, 9, 3]) == [2, 3, 5, 9] | |
assert merge_sort([5, 2, 9, 3, 34]) == [2, 3, 5, 9, 34] | |
assert merge_sort([12, 2, 3, 51, 1235, 399]) == [2, 3, 12, 51, 399, 1235] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment