
Python 实现快速排序
快速排序,排序中最基本的算法,也是用得最多的算法。
python 里的 sorted() 方法,就是使用快速排序来执行的。
原理
在数据中选定一个基准,将小于这个基准的的数据放在左边,大于这个基准的放在右边,然后以这个基准为分界线,递归地实现左边以及右边的数据。
这个基准可以选中位数,也可以选第一个以及最后一个数,不同的数会导致不同的执行效率。
实现
- 常见的实现代码
这个代码最好理解,也十分通用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
45def quick_sort(alist:list, low: int, high: int):
# 当 low 高于 high 的时候,出栈
if low >= high:
return
partition = get_partition_1(alist, low, high)
quick_sort(alist, low, partition-1)
quick_sort(alist, partition+1, high)
# 以第一个为基准
def get_partition_1(alist:list, low:int, high: int):
pivot = alist[low]
while low < high:
# 右边找到比基准小于等于的数
while low < high and alist[high] > pivot:
high -= 1
alist[low] = alist[high]
# 左边找到比基准大的数
while low < high and alist[low] <= pivot:
low += 1
alist[high] = alist[low]
alist[low] = pivot
return low
# 以最后一个为基准
def get_partition_2(alist:list, low:int, high: int):
pivot = alist[high]
while low < high:
# 左边找到比基准大于等于的数
while low < high and alist[low] < pivot:
low += 1
alist[high] = alist[low]
# 右边找到比基准小的数
while low < high and alist[high] >= pivot:
high -= 1
alist[low] = alist[high]
alist[high] = pivot
return high
还有一个是以中间为基准的代码:
1 | # 以中间为基准 |
- 单循环版
只使用单循环,代码更加简洁。
1 | def quick_sort(alist:list, low: int, high: int): |
- python简洁版
使用python的特性,以及分治算法。
1 | def quick_sort(alist: list): |
- 一行代码实现版
上面代码的简化版1
quick_sort = lambda array: array if len(array) <= 1 else quick_sort([item for item in array[1:] if item <= array[0]]) + [array[0]] + quick_sort([item for item in array[1:] if item > array[0]])
优化一下函数命名:
1 | sort = lambda A: A if len(A) <= 1 else sort([i for i in A[1:] if i <= A[0]]) + [A[0]] + sort([i for i in A[1:] if i > A[0]]) |