-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.py
More file actions
45 lines (35 loc) · 1.3 KB
/
QuickSort.py
File metadata and controls
45 lines (35 loc) · 1.3 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
def quick_sort(a_list):
quick_sort_helper(a_list, 0, len(a_list)-1)
def quick_sort_helper(a_list, first, last):
if first < last:
split_point = partition(a_list, first, last)
quick_sort_helper(a_list, first, split_point-1)
quick_sort_helper(a_list, split_point+1, last)
def partition(a_list, first, last):
# 基准
pivot_value = a_list[first]
left_mark = first + 1
right_mark = last
done = False
while not done:
# left_mark找到小于基准的数
while (left_mark <= right_mark and
a_list[left_mark] <= pivot_value):
left_mark = left_mark + 1
# right_mark找到大于基准的数
while (right_mark >= left_mark and
a_list[right_mark] >= pivot_value):
right_mark = right_mark - 1
# 停止条件
if right_mark < left_mark:
done = True
else:
a_list[left_mark], a_list[right_mark] = a_list[right_mark], a_list[left_mark]
# 将基准移到中间去,自此列表分成了两部分
a_list[first], a_list[right_mark] = a_list[right_mark], a_list[first]
# 返回基准所在位置
return right_mark
if __name__ == '__main__':
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quick_sort(a_list)
print(a_list)