Created
March 5, 2022 10:18
-
-
Save jiachen247/bb5c096e30f14ce44ef0e3104f5c6ecd to your computer and use it in GitHub Desktop.
Merge Sort Example
This file contains hidden or 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 mergeSort(arr): | |
def combine(L, R): | |
i = j = k = 0 | |
while i < len(L) and j < len(R): | |
if L[i] < R[j]: | |
arr[k] = L[i] | |
i += 1 | |
else: | |
arr[k] = R[j] | |
j += 1 | |
k += 1 | |
while i < len(L): | |
arr[k] = L[i] | |
i += 1 | |
k += 1 | |
while j < len(R): | |
arr[k] = R[j] | |
j += 1 | |
k += 1 | |
# base case (already sorted!) | |
if len(arr) == 1: | |
return arr | |
# Step 1: Split | |
mid = len(arr) // 2 | |
L = arr[:mid] | |
R = arr[mid:] | |
# Step 2: Sort halves recursively | |
mergeSort(L) | |
mergeSort(R) | |
# Step 3: Combine halves | |
combine(L, R) | |
return arr | |
lst = [38, 27, 43, 3, 9, 82, 10] | |
print(mergeSort(lst)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Condensed version