Skip to content

Commit 1d19ae1

Browse files
Adding merge sort algorithm
1 parent 8d56f10 commit 1d19ae1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

merge_sort.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def merge_sort(unsorted_list):
2+
if len(unsorted_list) <= 1:
3+
return unsorted_list
4+
# Find the middle point and devide it
5+
middle = len(unsorted_list) // 2
6+
left_list = unsorted_list[:middle]
7+
right_list = unsorted_list[middle:]
8+
9+
left_list = merge_sort(left_list)
10+
right_list = merge_sort(right_list)
11+
return list(merge(left_list, right_list))
12+
13+
# Merge the sorted halves
14+
def merge(left_half,right_half):
15+
res = []
16+
while len(left_half) != 0 and len(right_half) != 0:
17+
if left_half[0] < right_half[0]:
18+
res.append(left_half[0])
19+
left_half.remove(left_half[0])
20+
else:
21+
res.append(right_half[0])
22+
right_half.remove(right_half[0])
23+
if len(left_half) == 0:
24+
res = res + right_half
25+
else:
26+
res = res + left_half
27+
return res
28+
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
29+
print(merge_sort(unsorted_list))

0 commit comments

Comments
 (0)