Skip to content

Instantly share code, notes, and snippets.

@segunadeleye
Created July 13, 2019 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save segunadeleye/743a734dfd959099e2ac8204fc7cdcad to your computer and use it in GitHub Desktop.
Save segunadeleye/743a734dfd959099e2ac8204fc7cdcad to your computer and use it in GitHub Desktop.
An implementation of the merge sort algorithm in Python.
'''
The merge sort algorithm has a time complexity of O(nlogn).
It is an implementation of a Divide and Conquer rule.
'''
def mergeSort(array):
n = len(array)
if n == 1:
return array
mid = n // 2
left = array[0:mid]
right = array[mid:]
return merge(mergeSort(left), mergeSort(right), n)
def merge(left, right, n):
merged = []
iLeft = 0
iRight = 0
leftLength = len(left)
rightLength = len(right)
for i in range(n):
if iLeft >= leftLength:
merged.append(right[iRight])
iRight += 1
elif iRight >= rightLength:
merged.append(left[iLeft])
iLeft += 1
elif left[iLeft] <= right[iRight]:
merged.append(left[iLeft])
iLeft += 1
else:
merged.append(right[iRight])
iRight += 1
print(iLeft, iRight, merged)
return merged
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment