快速排序
def quicksort(data,left,right):
if left>=right:
return
i=left
j=right
temp=data[left]#要归位的元素
while i<j:
while i<j and data[j]>=temp:
j-=1
data[i]=data[j]#右边的都比temp大
while i<j and data[i]<=temp:
i+=1
data[j]=data[i]#左边的都比temp小
data[i]=temp#归位
quicksort(data,left,i-1)#排序i左边
quicksort(data,i+1,right)#排序i右边
def partition(data,i,j):
temp=data[i]#要归位的元素
while i<j:
while i<j and data[j]>=temp:
j-=1
data[i]=data[j]#右边的都比temp大
while i<j and data[i]<=temp:
i+=1
data[j]=data[i]#左边的都比temp小
data[i]=temp
return i
def quicksort(data,left,right):
if left>=right:
return
i=partition(data,left,right)#归位一个
quicksort(data,left,i-1)#排序i左边
quicksort(data,i+1,right)#排序i右边
过程图看这个:https://blog.csdn.net/nrsc272420199/article/details/82587933
分治,递归
最坏时间复杂度:
有序数组
T(n) = T(n-1)+T(n-2)+……+T(1) = (n-1)+(n-2)+……+1 = n(n-1)/2 = O(n^2)
最好时间复杂度:
T(1) = 1
T(n) = n+2T(n/2) = (k-1)n+2^kT(n/2^k) , 2^k=n , k=log2 n
T(n) = (log n-1)n+nT(1) = log n