mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
Added Merge Sort
This commit is contained in:
parent
0b8a494b62
commit
b9692267f9
36
MergeSort.py
Normal file
36
MergeSort.py
Normal 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)
|
||||
|
Loading…
Reference in New Issue
Block a user