-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick_sort.py
More file actions
58 lines (43 loc) · 1.55 KB
/
Copy pathquick_sort.py
File metadata and controls
58 lines (43 loc) · 1.55 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
56
57
58
from typing import List, Any
def _partition(seq: List[Any], lo: int, hi: int) -> int:
i = lo
for j in range(lo, hi):
if seq[j] < seq[hi]:
seq[i], seq[j] = seq[j], seq[i]
i += 1
seq[i], seq[hi] = seq[hi], seq[i]
return i
def _quick_sort(seq: List[Any], lo: int, hi: int) -> None:
if (lo < hi):
p = _partition(seq, lo, hi)
_quick_sort(seq, lo, p-1)
_quick_sort(seq, p+1, hi)
def quick_sort(seq: List[Any]) -> None:
_quick_sort(seq, 0, len(seq) - 1)
if __name__ == "__main__":
sorting_fn = quick_sort
def is_sorted(seq: List[Any]) -> bool:
for i in range(len(seq)-1):
if seq[i] > seq[i+1]:
return False
return True
# empty
seq = []
sorting_fn(seq)
print(f"test_empty: {'passed' if is_sorted(seq) else 'failed'}.")
# +
seq = [16, 7, 9, 5, 65, 49, 37, 3, 28, 2, 21, 12, 4]
sorting_fn(seq)
print(f"test_int_1: {'passed' if is_sorted(seq) else 'failed'}.")
# +, -
seq = [-16, 7, -9, 5, -65, 49, -37, 3, -28, 2, -21, 12, -4]
sorting_fn(seq)
print(f"test_int_2: {'passed' if is_sorted(seq) else 'failed'}.")
# +, -, =
seq = [1, 2, -4, -7, 1, 9, -7, 2, 2, 6, 1, 12, 4]
sorting_fn(seq)
print(f"test_int_3: {'passed' if is_sorted(seq) else 'failed'}.")
# string
seq = ["p", "g", "i", "j", "65", "W", "K", "c", "B", "b", "21", "l", "d"]
sorting_fn(seq)
print(f"test_str: {'passed' if is_sorted(seq) else 'failed'}.")