I’m trying to implement quicksort in Python using 2 main functions – partition and quicksort.
The partition function is designed so that it returns 2 arrays – bigger and smaller than p.
after that quicksort is called on both of them separately.
so the quicksort works like this:
def quicksort(array)
pivot = 0 # pivot choice is irrelevant
left,right = partition(array,pivot)
quicksort(left)
quicksoft(right)
return left+right
But from my understanding it should be possible to design partition to return just one single index – delimiting bigger and smaller arrays and redesign quicksort as follows:
def quicksort(array)
pivot = 0 # pivot choice is irrelevant
i = partition(array,pivot)
quicksort(array[:i-1])
quicksoft(array[i:])
return array
but this implementation returns partially sorted array
original array [5, 4, 2, 1, 6, 7, 3, 8, 9]
sorted array [3, 4, 2, 1, 5, 7, 6, 8, 9]
what am i missing here?
without seeing your code it’s hard to be sure, but one possible error is the
i-1:(although you may be simply skipping the pivot?)
also, slices are new lists, not views:
which is unfortunate (the typical functional program doing quicksort which is not a quicksort at all, dammit, because it’s creating a pile of new arrays annoys me too…)
you can work round the second problem by passing the entire list plus lo/hi indices: