-
Notifications
You must be signed in to change notification settings - Fork 0
/
mergeSort.py
34 lines (26 loc) · 847 Bytes
/
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
def merge(array, left, right, ascending):
i = j = 0
if ascending:
while i + j < len(array):
if j == len(right) or (i < len(left) and left[i] < right[j]):
array[i + j] = left[i]
i += 1
else:
array[i + j] = right[j]
j += 1
else:
while i + j < len(array):
if j == len(right) or (i < len(left) and left[i] > right[j]):
array[i + j] = left[i]
i += 1
else:
array[i + j] = right[j]
j += 1
def merge_sort(array, ascending=True):
r = len(array)
if r >= 2:
q = r // 2
left, right = array[:q], array[q:]
merge_sort(left, ascending)
merge_sort(right, ascending)
merge(array, left, right, ascending)