Created
June 1, 2021 07:01
-
-
Save wilderfield/d23cd73ab1fdc0289ca6b04a0de32941 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
# This approach does not sort nums in place | |
def merge(numsLeft, numsRight): | |
result = [] | |
i = 0 | |
j = 0 | |
while i < len(numsLeft) and j < len(numsRight): | |
if numsLeft[i] <= numsRight[j]: | |
result.append(numsLeft[i]) | |
i += 1 | |
else: | |
result.append(numsRight[j]) | |
j += 1 | |
while i < len(numsLeft): | |
result.append(numsLeft[i]) | |
i += 1 | |
while j < len(numsRight): | |
result.append(numsRight[j]) | |
j += 1 | |
return result | |
def mergeSortH(nums, l, r): | |
if l == r: | |
return [nums[l]] | |
m = l + (r-l)/2 | |
L = mergeSortH(nums, l, m) | |
R = mergeSortH(nums, m + 1, r) | |
return merge(L,R) | |
def mergeSort(nums): | |
return mergeSortH(nums, 0, len(nums) - 1) | |
nums = [5, 3, 8, 6, 2, 1, 0, 9, 7, 4] | |
print nums | |
print mergeSort(nums) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment