-
-
Save alexwal/bb0349cf74bb0cb4a66bae7edbd8f964 to your computer and use it in GitHub Desktop.
Recursive Mergesort in Python
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
# Alex Walczak, 2017 | |
# Simple recursive merge sort implementation. | |
def merge(left, right): | |
if not (len(left) and len(right)): | |
return left or right | |
result = [] | |
i = j = 0 | |
while len(result) < len(left) + len(right): | |
if i == len(left) or j == len(right): | |
result.extend(left[i:] or right[j:]) | |
elif left[i] < right[j]: | |
result.append(left[i]) | |
i += 1 | |
else: | |
result.append(right[j]) | |
j += 1 | |
return result | |
def mergesort(A): | |
if len(A) <= 1: | |
return A | |
return merge(mergesort(A[:len(A) // 2]), mergesort(A[len(A) // 2:])) | |
if __name__ == '__main__': | |
A = [5, 1, 9, 3, 2, 4, 6, 8, 7] | |
print(mergesort(A)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment