Created
March 20, 2022 12:13
-
-
Save Weizhang2017/2e56e58a2d25147b7617f1f8a2c274b5 to your computer and use it in GitHub Desktop.
Merge Sort
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) >= 2: | |
mid = len(array) // 2 | |
left = merge_sort(array[:mid]) | |
right = merge_sort(array[mid:]) | |
return merge(left, right) | |
else: | |
return array | |
def merge(left, right): | |
i = j = 0 | |
A = [] | |
while i < len(left) and j < len(right): | |
if left[i] < right[j]: | |
A.append(left[i]) | |
i += 1 | |
else: | |
A.append(right[j]) | |
j += 1 | |
if i < len(left): | |
A += left[i:] | |
elif j < len(right): | |
A += right[j:] | |
return A |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment