-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge sort.py
56 lines (41 loc) · 1.59 KB
/
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# merge sort - O(n * log(n, 2))
#
import random
def merge_sort(array):
if len(array) > 1:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
print('array after separating, left:', left, ', right:', right)
left = merge_sort(left)
right = merge_sort(right)
print(' after recursion stop we have, left:', left, ', right:', right)
sorted_array = []
while len(left) > 0 and len(right) > 0:
if left[0] < right[0]:
sorted_array.append(left.pop(0))
print(' after popping one element, left:', left)
print(' after popping one element, left, sorted array:', sorted_array)
else:
sorted_array.append(right.pop(0))
print(' after popping one element, right:', right)
print(' after popping one element, right, sorted array:', sorted_array)
for i in left:
sorted_array.append(i)
print(' after adding from left element to sorted array:', sorted_array)
for i in right:
sorted_array.append(i)
print(' after adding from right element sorted array:', sorted_array)
print()
else:
sorted_array = array
return sorted_array
if __name__ == '__main__':
array = []
array_len = random.randint(5, 6)
for i in range(array_len):
array.append(random.randint(1, 10))
print(array)
sorted_array = merge_sort(array)
print('array before sorting:', array)
print('array after sorting:', sorted_array)