Skip to content

Commit 3f71e36

Browse files
authored
Create MergeSort.py
1 parent 98701cd commit 3f71e36

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Sorting/MergeSort.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class MergeSort:
2+
3+
def __init__(self, lst):
4+
self.lst = lst
5+
6+
def mergeSort(self, a):
7+
midPoint = len(a)//2
8+
if a[len(a)-1] < a[0]:
9+
left = self.mergeSort(a[:midPoint])
10+
right = self.mergeSort(a[midPoint:])
11+
return self.merge(left, right)
12+
else:
13+
return a
14+
15+
def merge(self, left, right):
16+
output = list()
17+
leftCount, rightCount = 0, 0
18+
while leftCount < len(left) or rightCount < len(right):
19+
if leftCount < len(left) and rightCount < len(right):
20+
if left[leftCount] < right[rightCount]:
21+
output.append(left[leftCount])
22+
leftCount += 1
23+
else:
24+
output.append(right[rightCount])
25+
rightCount += 1
26+
if leftCount == len(left) and rightCount < right(right):
27+
output.append(right[rightCount])
28+
rightCount += 1
29+
elif leftCount < len(left) and rightCount == len(right):
30+
output.append(left[leftCount])
31+
leftCount += 1
32+
return output
33+
34+
def sort(self):
35+
temp = self.mergeSort(self.lst)
36+
self.lst = temp
37+
38+
def show(self):
39+
return self.lst
40+
41+
if __name__ == "__main__":
42+
i = MergeSort([5,4,3,2,1])
43+
i.sort()
44+
print i.show()

0 commit comments

Comments
 (0)