def partition(A,lo,hi):
pivot = A[hi]
i=lo
#Swap
for j in range(lo,hi-1):
if (A[j] <= pivot):
val=A[i]
A[i]=A[j]
A[j]=val
i=i+1
val=A[i]
A[i]=A[hi]
A[hi]=val
return(i)
def quicksort(A,lo,hi):
if (lo<hi):
p=partition(A,lo,hi)
quicksort(A,lo,p-1)
quicksort(A,p+1,hi)
return(A)
如果我的输入为[5,3,2,6,8,9,1]
,则输出为[1, 2, 5, 3, 8, 9, 6]
,为什么会这样?
答案 0 :(得分:2)
def partition(A,lo,hi):
pivot = A[hi]
i=lo
#Swap
for j in range(lo,hi-1):
if (A[j] <= pivot):
val=A[i]
A[i]=A[j]
A[j]=val
i=i+1
val=A[i] #was in for loop was suppose to be outside of for loop
A[i]=A[hi] #was in for loop was suppose to be outside of for loop
A[hi]=val #was in for loop was suppose to be outside of for loop
return(i)
def quicksort(A,lo,hi):
if (lo<hi):
p=partition(A,lo,hi)
quicksort(A,lo,p-1)
quicksort(A,p+1,hi)
return(A)
x = [5,3,2,6,8,9,1]
print(quicksort(x,0,len(x)-1))
简单修复,你的缩进在分区中是错误的。
输出
[1, 2, 3, 5, 6, 8, 9]