思路
随机选择一个值,一般称之为pivot,之后和这个pivot进行大小比较,把较小的放在一起,较大的放在一起,递归实现。
- 时间复杂度:O(nlogn),是冒泡排序的一种改进。
- 空间复杂度:O(logn),
- 非稳定排序
- 原地排序
Python代码
def quicksort(collection):
length = len(collection)
if length <= 1: # 如果小于等于1,那么直接返回,两种情况,空和有序(单值一定有序)
return collection
pivot = collection[0] # 选定列表的第一个值作为pivot
less = [ele for ele in collection[1:] if ele < pivot] # 把小于pivot的值放在一起
more = [ele for ele in collection[1:] if ele >= pivot] # 把大于pivot的值放在一起
return quicksort(less) + [pivot] + quicksort(more) # 递归
if __name__ == '__main__':
print(quicksort([0, 5, 3, 2])) # 测试输出为[0, 2, 3, 5]