forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.py
65 lines (54 loc) · 1.44 KB
/
merge_sort.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
Author: Wenru
"""
from typing import List
def merge_sort(a: List[int]):
_merge_sort_between(a, 0, len(a) - 1)
def _merge_sort_between(a: List[int], low: int, high: int):
# The indices are inclusive for both low and high.
if low < high:
mid = low + (high - low) // 2
_merge_sort_between(a, low, mid)
_merge_sort_between(a, mid + 1, high)
_merge(a, low, mid, high)
def _merge(a: List[int], low: int, mid: int, high: int):
# a[low:mid], a[mid+1, high] are sorted.
i, j = low, mid + 1
tmp = []
while i <= mid and j <= high:
if a[i] <= a[j]:
tmp.append(a[i])
i += 1
else:
tmp.append(a[j])
j += 1
start = i if i <= mid else j
end = mid if i <= mid else high
tmp.extend(a[start:end + 1])
a[low:high + 1] = tmp
def test_merge_sort():
a1 = [3, 5, 6, 7, 8]
merge_sort(a1)
assert a1 == [3, 5, 6, 7, 8]
a2 = [2, 2, 2, 2]
merge_sort(a2)
assert a2 == [2, 2, 2, 2]
a3 = [4, 3, 2, 1]
merge_sort(a3)
assert a3 == [1, 2, 3, 4]
a4 = [5, -1, 9, 3, 7, 8, 3, -2, 9]
merge_sort(a4)
assert a4 == [-2, -1, 3, 3, 5, 7, 8, 9, 9]
if __name__ == "__main__":
a1 = [3, 5, 6, 7, 8]
a2 = [2, 2, 2, 2]
a3 = [4, 3, 2, 1]
a4 = [5, -1, 9, 3, 7, 8, 3, -2, 9]
merge_sort(a1)
print(a1)
merge_sort(a2)
print(a2)
merge_sort(a3)
print(a3)
merge_sort(a4)
print(a4)