-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.py
43 lines (31 loc) · 1.06 KB
/
MergeSort.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
# It was hard
import random
arr = [random.randrange(100) for i in range(10)] # Generate random list
def checkSort(array) -> bool: # Function for check sort status
for i in range(len(array) - 1):
if array[i] > array[i + 1]: # If all elements less than the following then sorted is True
return True
return False
def sort(a, b):
if a > b:
return b, a
else:
return a, b
def sortArr(a, b) -> list:
array = a + b
done = True
while done:
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
array[i], array[i + 1] = sort(array[i], array[i + 1])
done = checkSort(array)
return array
def merge(array):
firstArr = [array[i] for i in range(len(array) // 2)]
secondArr = [array[i] for i in range(len(array) // 2, len(array))]
if len(firstArr) > 2 or len(secondArr) > 2:
return sortArr(merge(firstArr), merge(secondArr))
else:
return sortArr(firstArr, secondArr)
print(arr)
print(merge(arr))