Created
June 7, 2019 13:41
-
-
Save Yossarian0916/1cb08ed7d29b821cb8446ec91231a34b to your computer and use it in GitHub Desktop.
merge sort python implementation
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 | |
else: | |
mid = len(array) // 2 | |
left = merge_sort(array[:mid]) | |
right = merge_sort(array[mid:]) | |
return merge(left, right) | |
def merge(left, right): | |
res = [] | |
i = j = 0 | |
while i < len(left) and j < len(right): | |
if left[i] < right[j]: | |
res.append(left[i]) | |
i += 1 | |
elif left[i] >= right[j]: | |
res.append(right[j]) | |
j += 1 | |
res += left[i:] | |
res += right[j:] | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment