快速排序
算法步骤
- 找一个基准值,将这个基准值放在正确的位置上,也就是左边的都比它小,右边都比它大,至于左右两边的顺序先不管。
- 此时数列已经被分为了两个部分,再在左右两边重复第一步,直到数列的顺序被排好。
动图演示
代码实现
def quick_sort(ls,left,right):
if left>right: #递归停止的条件
return
cur=ls[left]
low=left
high=right
while low<high:
if ls[high]>=cur:
high-=1
else:
ls[low]=ls[high]
while low<high and ls[low]<=cur:
low+=1
ls[high]=ls[low]
ls[low]=cur
quick_sort(ls,left,low-1)
quick_sort(ls,low+1,right)
ls=[63,23,23,67,78,45,23,89,10,19,91,68,10,10,23,100,89,98]
quick_sort(ls,0,len(ls)-1)
print(ls)
# [10, 10, 10, 19, 23, 23, 23, 23, 45, 63, 67, 68, 78, 89, 89, 91, 98, 100]
, 67, 68, 78, 89, 89, 91, 98, 100]