-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerinssort.py
More file actions
55 lines (48 loc) · 1.21 KB
/
merinssort.py
File metadata and controls
55 lines (48 loc) · 1.21 KB
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
import random
def msort(list):
if len(list) > 1:
mid = len(list) // 2
lefthalf = list[:mid]
righthalf = list[mid:]
msort(lefthalf)
msort(righthalf)
i = j = k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
list[k] = lefthalf[i]
i += 1
else:
list[k] = righthalf[j]
j += 1
k += 1
while i < len(lefthalf):
list[k] = lefthalf[i]
i += 1
k += 1
while j < len(righthalf):
list[k] = righthalf[j]
j += 1
k += 1
return list
def insort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
list = []
for i in range(10):
list.append(random.randint(0, 999))
print("Unsorted list :\n", list)
print("Sorting using insertion sort:")
insort(list)
print(list)
list = []
for i in range(10):
list.append(random.randint(0, 999))
print("Unsorted list :\n", list)
print("Sorting using merge sort:")
msort(list)
print(list)