<pre name="code" class="python">def quick_sort(A,p,r):
if p<r:
q=partition(A,p,r)
quick_sort(A,p,q-1)
quick_sort(A,q+1,r)
def partition(A,p,r):
x=A[r] # x is pivot
#invariant
# A[p,i]<=x A(i,j)>=x A[j,r] unexplored
# initial i=p-1 j=p
# terminate j=r so A[p,i]<=x<=A(i,r]
i=p-1
for j in range(p,r):
if A[j]<=x:
i+=1
A[i],A[j]=A[j],A[i]
A[i+1],A[r]=A[r],A[i+1]
return i+1
A=[2,8,7,1,3,5,6,4]
quick_sort(A,0,len(A)-1)
print(A)
quicksort in clrs
最新推荐文章于 2022-09-29 11:36:17 发布