-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathquick_sort.py
More file actions
38 lines (34 loc) · 1.02 KB
/
quick_sort.py
File metadata and controls
38 lines (34 loc) · 1.02 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def quick_sort(arr):
less = []
pivot_list = []
more = []
# 递归出口
if len(arr) <= 1:
return arr
else:
# 将第一个值做为基准
pivot = arr[0]
for i in arr:
# 将比急转小的值放到less数列
if i < pivot:
less.append(i)
# 将比基准打的值放到more数列
elif i > pivot:
more.append(i)
# 将和基准相同的值保存在基准数列
else:
pivot_list.append(i)
# 对less数列和more数列继续进行排序
less = quick_sort(less)
more = quick_sort(more)
return less + pivot_list + more
def quick_sort_cookbook(arr):
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
return quick_sort_cookbook([x for x in arr[1:] if x < pivot]) + \
[pivot] + \
quick_sort_cookbook([x for x in arr[1:] if x >= pivot])