Created
October 17, 2018 06:33
-
-
Save scientificRat/835e5ad2c9a2196da31c8af1491aee2a to your computer and use it in GitHub Desktop.
merge_sort implementation 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
def merge_sort(array): | |
if len(array) == 1: | |
return [array[0]] | |
elif len(array) == 2: | |
if array[0] > array[1]: | |
return [array[1], array[0]] | |
return [array[0], array[1]] | |
mid = len(array) // 2 | |
left = merge_sort(array[0:mid]) | |
right = merge_sort(array[mid:]) | |
# merge | |
out = [] | |
i, j = 0, 0 | |
while i < len(left) and j < len(right): | |
if left[i] < right[j]: | |
out.append(left[i]) | |
i += 1 | |
else: | |
out.append(right[j]) | |
j += 1 | |
while i < len(left): | |
out.append(left[i]) | |
i += 1 | |
while j < len(right): | |
out.append(right[j]) | |
j += 1 | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment