-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergesort.py
More file actions
36 lines (31 loc) · 771 Bytes
/
mergesort.py
File metadata and controls
36 lines (31 loc) · 771 Bytes
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
def mergesort(s):
if len(s) > 1:
mid = len(s) // 2
left = s[:mid]
right = s[mid:]
mergesort(left)
mergesort(right)
i = j = k = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
s[k] = left[i]
i += 1
else:
s[k] = right[j]
j += 1
k += 1
while i < len(left):
s[k] = left[i]
i += 1
k += 1
while j < len(right):
s[k] = right[j]
j += 1
k += 1
import random
array = []
for i in range(20):
array.append(random.randint(1, 9))
print("Unsorted array: ", array)
mergesort(array)
print("Sorted array: ", array)