Created
October 16, 2022 02:27
-
-
Save esamson33/ea9fd66f6a2dea02a30c0f0a5688316b to your computer and use it in GitHub Desktop.
Merge sort 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(lst): | |
""" | |
Performs in-place sorting using the merge sort algorithm | |
""" | |
if len(lst) > 1: | |
mid = len(lst) // 2 | |
left = lst[:mid] | |
right = lst[mid:] | |
merge_sort(left) | |
merge_sort(right) | |
i = 0 # left iterator | |
j = 0 # right iterator | |
k = 0 # dest iterator | |
while i < len(left) and j < len(right): | |
if left[i] < right[j]: | |
lst[k] = left[i] | |
i += 1 | |
else: | |
lst[k] = right[j] | |
j += 1 | |
k += 1 | |
while i < len(left): | |
lst[k] = left[i] | |
i += 1 | |
k += 1 | |
while j < len(right): | |
lst[k] = right[j] | |
j += 1 | |
k += 1 | |
lst = [4,5,7,8,3,2,1,8,9,3] | |
merge_sort(lst) | |
print(lst) # [1, 2, 3, 3, 4, 5, 7, 8, 8, 9] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment