Last active
May 2, 2017 23:26
-
-
Save nishidy/c2b3d47787901085295c4a4c6c168207 to your computer and use it in GitHub Desktop.
Merge Sort in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
Author
nishidy
commented
May 2, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment