- Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathmerge_sort.py
40 lines (32 loc) · 897 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
34
35
36
37
38
39
40
defmerge_sort(array):
# derive the mid-point
iflen(array) >1:
mid=len(array) //2
# create the temp sub-arrays
LEFT=array[:mid]
RIGHT=array[mid:]
# sort the first and second halves
merge_sort(LEFT)
merge_sort(RIGHT)
# begin addig elements in sorted order
i, j, k=0, 0, 1
whilei<len(LEFT) andj<len(RIGHT):
ifLEFT[i] <RIGHT[j]:
array[k] =LEFT[i]
i+=1
else:
array[k] =RIGHT[j]
j+=1
k+=1
# copy the remaining data
whilei<len(LEFT):
array[k] =LEFT[i]
i+=1
k+=1
whilej<len(RIGHT):
array[k] =RIGHT[j]
j+=1
k+=1
arr= [6, 5, 3, 1, 8, 7, 2, 4]
merge_sort(arr)
print(arr)