Skip to content

Commit ab44380

Browse files
authored
Create mergesort.md
Program of Merge Sort
1 parent 99cf7d7 commit ab44380

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

mergesort.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
def mergeSort(myList):
2+
if len(myList) > 1:
3+
mid = len(myList) // 2
4+
left = myList[:mid]
5+
right = myList[mid:]
6+
7+
# Recursive call on each half
8+
mergeSort(left)
9+
mergeSort(right)
10+
11+
# Two iterators for traversing the two halves
12+
i = 0
13+
j = 0
14+
15+
# Iterator for the main list
16+
k = 0
17+
18+
while i < len(left) and j < len(right):
19+
if left[i] < right[j]:
20+
# The value from the left half has been used
21+
myList[k] = left[i]
22+
# Move the iterator forward
23+
i += 1
24+
else:
25+
myList[k] = right[j]
26+
j += 1
27+
# Move to the next slot
28+
k += 1
29+
30+
# For all the remaining values
31+
while i < len(left):
32+
myList[k] = left[i]
33+
i += 1
34+
k += 1
35+
36+
while j < len(right):
37+
myList[k]=right[j]
38+
j += 1
39+
k += 1
40+
41+
myList = [54,26,93,17,77,31,44,55,20]
42+
mergeSort(myList)
43+
print(myList)

0 commit comments

Comments
 (0)