# Time complexity is O(nlogn)
def merge_sort(sequence):
if len(sequence) > 1: # run if the sequence is greater than 1
= sequence[:len(sequence)//2]
left_array = sequence[len(sequence)//2:]
right_array
# Recursively split the array
merge_sort(left_array)
merge_sort(right_array)
# Merge the array
= 0
i = 0
j = 0
k
while i < len(left_array) and j < len(right_array):
if left_array[i] < right_array[j]:
= left_array[i]
sequence[k] += 1
i
else :
= right_array[j]
sequence[k] += 1
j
+= 1
k
# If the lenght of the left array is greater than right array,
# append the elements in left array to the sequence
while i < len(left_array):
= left_array[i]
sequence[k] += 1
i += 1
k
# If the lenght of the right array is greater than left array,
# append the elements in right array to the sequence
while j < len(right_array):
= right_array[j]
sequence[k] += 1
j += 1
k
return sequence
Merge Sort
# Check if the function is working correct
= [5,8,3,9,5,0,9,387,9486,9,4,56] array_test
merge_sort(array_test)
[0, 3, 4, 5, 5, 8, 9, 9, 9, 56, 387, 9486]