def quicksort(a,start,end):
if(start<end):
#print(start,end)
p_index = partition(a,start,end)
quicksort(a,start,p_index-1)
quicksort(a,p_index+1,end)
def partition(a,start,end):
pivot = a[end]
pindex = start
for i in range(start,end):
if (a[i]<= pivot):
a[pindex],a[i]=a[i],a[pindex]
pindex = pindex+1
a[pindex],a[pivot]=a[pivot],a[pindex]
print(pindex)
return pindex
a = [7,6,5,0]
quicksort(a,0,3)
print(a)
this implementation is giving out the wrong output. Correct me where I'm doing it wrong.
The line in your partition
function where you swap the pivot element into its final position is incorrect. pivot
is the value of the pivot element, not its index. The index of the pivot at that point is still end
.
Change:
a[pindex],a[pivot]=a[pivot],a[pindex]
to:
a[pindex],a[end]=a[end],a[pindex]
or maybe:
a[end] = a[pindex] # we don't need to do a simultaneous swap because we already
a[pindex] = pivot # have a separate reference to the value of the pivot element
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.