Skip to content

Commit 2b23c8a

Browse files
committed
Added Merge Sort
1 parent d17213e commit 2b23c8a

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

python/sorting/merge_sort.py

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+
myArr = list(map(int, input("Enter elements of the array(space-separated): ").split()))
42+
mergeSort(myArr)
43+
print(myArr)

0 commit comments

Comments
 (0)