Skip to content

Instantly share code, notes, and snippets.

@Auax
Created November 24, 2024 12:25
Show Gist options
  • Save Auax/0fb14cd353e2f5f8d776380f04ba3d5d to your computer and use it in GitHub Desktop.
Save Auax/0fb14cd353e2f5f8d776380f04ba3d5d to your computer and use it in GitHub Desktop.
Merge sort algorithm implementation in Python
def mergesort(array: list):
"""
Sorts an array in ascending order using the merge sort algorithm.
The array is recursively split into two halves until each half contains a single element.
Then, these halves are merged back together in sorted order using the `merge` function.
Parameters
----------
array : list
The list of elements to be sorted.
"""
length = len(array)
# If we cannot split the list further, stop.
# Base case
if length <= 1:
return
middle = length // 2
left_array = [0] * middle
right_array = [0] * (length - middle)
j = 0
for i in range(length):
if (i < middle):
left_array[i] = array[i]
else:
right_array[j] = array[i]
j += 1
mergesort(left_array)
mergesort(right_array)
merge(left_array, right_array, array)
def merge(left_array, right_array, array):
"""
Merges two sorted sub-arrays into a single sorted array.
This function takes two sorted sub-arrays, `left_array` and `right_array`,
and merges them into `array` in sorted order. It assumes that `left_array`
and `right_array` are the left and right halves of `array`, respectively.
Parameters
----------
left_array : list
The left sorted sub-array.
right_array : list
The right sorted sub-array.
array : list
The array where the merged result is stored.
"""
left_size = len(array) // 2
right_size = len(array) - left_size
i = 0 # Array index
l = 0 # Left array index
r = 0 # Right array index
while (l < left_size and r < right_size):
if (left_array[l] < right_array[r]):
array[i] = left_array[l]
i += 1
l += 1
else:
array[i] = right_array[r]
i += 1
r += 1
# Fill in the remaining elements
while (l < left_size):
array[i] = left_array[l]
i += 1
l += 1
while (r < right_size):
array[i] = right_array[r]
i += 1
r += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment