Skip to content

Instantly share code, notes, and snippets.

@esamson33
Created October 16, 2022 02:27
Show Gist options
  • Save esamson33/ea9fd66f6a2dea02a30c0f0a5688316b to your computer and use it in GitHub Desktop.
Save esamson33/ea9fd66f6a2dea02a30c0f0a5688316b to your computer and use it in GitHub Desktop.
Merge sort in Python
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