-
Notifications
You must be signed in to change notification settings - Fork 26
/
Merge_Sort.py
34 lines (28 loc) · 928 Bytes
/
Merge_Sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def merge_sort(unsorted_list):
if len(unsorted_list) <= 1:
return unsorted_list
# Find the middle point and divide the unsorted list
middle = len(unsorted_list) // 2
left_list = unsorted_list[:middle]
right_list = unsorted_list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
# Merge the sorted halves
def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
del left_half[0]
else:
res.append(right_half[0])
del right_half[0]
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
# You can add any list of numbers here
unsorted_list = [6,5,3,1,8,7,2,4]
print(merge_sort(unsorted_list))