快速排序
Python的快排不超过10行
def qsort(array):
if len < 2:
return array
else:
pivot = array[0]
less = [i for i in array[1:] if i <= pivot]
greater = [i for i in array[1:] if i > pivot]
return qsort(less) + [pivot] + qsort(greater)
每个子问题都是以首元素为基准值来分块的,而实际上快速排序的基准值是随意的,但都有效,刚才的写法比较简洁,下面是比较好明白的写法:
def qsort(array):
if len(array)<2:
return array
else:
less = []
greater = []
pivot = array[0]
for i in array[1:]:
if i <= pivot:
less.append(i)
else:
greater.append(i)
return qsort(less) + [pivot] + qsort(greater)
调用函数得到的结果
print(qsort([-1,1,5,9,-3,8,4,10,3]))
>>>[-3, -1, 1, 3, 4, 5, 8, 9, 10]