Skip to content

Instantly share code, notes, and snippets.

@nishidy
Last active May 2, 2017 23:26
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 nishidy/c2b3d47787901085295c4a4c6c168207 to your computer and use it in GitHub Desktop.
Save nishidy/c2b3d47787901085295c4a4c6c168207 to your computer and use it in GitHub Desktop.
Merge Sort in Python
class Sorter:
def __init__(self,data):
self.data = data
def do_msort(self):
print("Original data",self.data)
self.run_msort(0,len(self.data)-1)
print("Sorted data ",self.data)
def run_msort(self,i,j):
if j-i==0:
return
m = int((i+j)/2)
self.run_msort(i,m)
self.run_msort(m+1,j)
tmp = []
p=i
q=m+1
while p<=m or q<=j:
if p<=m and q<=j:
if self.data[p] < self.data[q]:
tmp.append(self.data[p])
p+=1
else:
tmp.append(self.data[q])
q+=1
else:
if p<=m:
tmp.append(self.data[p])
p+=1
else:
tmp.append(self.data[q])
q+=1
self.data[i:j+1] = tmp
Sorter([5,3,1,0,2,4,9,7,8,6]).do_msort()
Sorter([9,8,7,6,5,4,3,2,1,0]).do_msort()
Sorter([2,2,2,2,1,1,1,1,0,0]).do_msort()
@nishidy
Copy link
Author

nishidy commented May 2, 2017

$ python merge_sort.py
Original data [5, 3, 1, 0, 2, 4, 9, 7, 8, 6]
Sorted data   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Original data [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Sorted data   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Original data [2, 2, 2, 2, 1, 1, 1, 1, 0, 0]
Sorted data   [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment