Skip to content
This repository has been archived by the owner on Nov 14, 2022. It is now read-only.

Create mergesort.py #739

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions mergesort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
def mergeSort(array):
if len(array) > 1:

# r is the point where the array is divided into two subarrays
r = len(array)//2
L = array[:r]
M = array[r:]

# Sort the two halves
mergeSort(L)
mergeSort(M)

i = j = k = 0

# Until we reach either end of either L or M, pick larger among
# elements L and M and place them in the correct position at A[p..r]
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1

# When we run out of elements in either L or M,
# pick up the remaining elements and put in A[p..r]
while i < len(L):
array[k] = L[i]
i += 1
k += 1

while j < len(M):
array[k] = M[j]
j += 1
k += 1


# Print the array
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()


# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]

mergeSort(array)

print("Sorted array is: ")
printList(array)