-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray_mergeSort.py
44 lines (33 loc) · 926 Bytes
/
array_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
def mergeSort(arr):
if len(arr) == 1:
return arr
middle = len(arr) // 2
left = arr[:middle]
right = arr[middle:]
left_result = mergeSort(left)
right_result = mergeSort(right)
return merge(left_result, right_result)
def merge(left_result, right_result):
result = [None] * (len(left_result) + len(right_result))
i = j = k = 0
while i < len(left_result) and j < len(right_result):
if left_result[i] <= right_result[j]:
result[k] = left_result[i]
i += 1
else:
result[k] = right_result[j]
j += 1
k += 1
while i < len(left_result):
result[k] = left_result[i]
i += 1
k += 1
while j < len(right_result):
result[k] = right_result[j]
j += 1
k += 1
return result
arr = [50, 40, 30, 20, 10]
print(arr)
print('sorted array:')
print(mergeSort(arr))