Added Merge Sort

This commit is contained in:
Chetan Kaushik 2016-07-24 17:19:09 +05:30
parent 0b8a494b62
commit b9692267f9

36
MergeSort.py Normal file
View File

@ -0,0 +1,36 @@
def mergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
while i < len(lefthalf):
alist[k]=lefthalf[i]
i=i+1
k=k+1
while j < len(righthalf):
alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
print("Enter numbers seprated by space")
s = input()
numbers = list(map(int, s.split()))
mergeSort(numbers)