forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorts.py
105 lines (84 loc) · 2.34 KB
/
sorts.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""
Bubble sort, insertion sort and selection sort
冒泡排序、插入排序、选择排序
Author: Wenru
"""
from typing import List
# 冒泡排序
def bubble_sort(a: List[int]):
length = len(a)
if length <= 1:
return
for i in range(length):
made_swap = False
for j in range(length - i - 1):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
made_swap = True
if not made_swap:
break
# 插入排序
def insertion_sort(a: List[int]):
length = len(a)
if length <= 1:
return
for i in range(1, length):
value = a[i]
j = i - 1
while j >= 0 and a[j] > value:
a[j + 1] = a[j]
j -= 1
a[j + 1] = value
# 选择排序
def selection_sort(a: List[int]):
length = len(a)
if length <= 1:
return
for i in range(length):
min_index = i
min_val = a[i]
for j in range(i, length):
if a[j] < min_val:
min_val = a[j]
min_index = j
a[i], a[min_index] = a[min_index], a[i]
def test_bubble_sort():
test_array = [1, 1, 1, 1]
bubble_sort(test_array)
assert test_array == [1, 1, 1, 1]
test_array = [4, 1, 2, 3]
bubble_sort(test_array)
assert test_array == [1, 2, 3, 4]
test_array = [4, 3, 2, 1]
bubble_sort(test_array)
assert test_array == [1, 2, 3, 4]
def test_insertion_sort():
test_array = [1, 1, 1, 1]
insertion_sort(test_array)
assert test_array == [1, 1, 1, 1]
test_array = [4, 1, 2, 3]
insertion_sort(test_array)
assert test_array == [1, 2, 3, 4]
test_array = [4, 3, 2, 1]
insertion_sort(test_array)
assert test_array == [1, 2, 3, 4]
def test_selection_sort():
test_array = [1, 1, 1, 1]
selection_sort(test_array)
assert test_array == [1, 1, 1, 1]
test_array = [4, 1, 2, 3]
selection_sort(test_array)
assert test_array == [1, 2, 3, 4]
test_array = [4, 3, 2, 1]
selection_sort(test_array)
assert test_array == [1, 2, 3, 4]
if __name__ == "__main__":
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
bubble_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
insertion_sort(array)
print(array)
array = [5, 6, -1, 4, 2, 8, 10, 7, 6]
selection_sort(array)
print(array)