I am totally new to python and I am trying to implement quicksort in it. Could someone please help me complete my code?
I do not know how to concatenate the three arrays and printing them.
def sort(array=[12,4,5,6,7,3,1,15]):
less = []
equal = []
greater = []
if len(array) > 1:
pivot = array[0]
for x in array:
if x < pivot:
less.append(x)
if x == pivot:
equal.append(x)
if x > pivot:
greater.append(x)
sort(less)
sort(pivot)
sort(greater)
A "true" in-place implementation [Algorithms 8.9, 8.11 from the Algorithm Design and Applications Book by Michael T. Goodrich and Roberto Tamassia]:
This is a version of the quicksort using Hoare partition scheme and with fewer swaps and local variables
I know many people have answered this question correctly and I enjoyed reading them. My answer is almost the same as zangw but I think the previous contributors did not do a good job of explaining visually how things actually work...so here is my attempt to help others that might visit this question/answers in the future about a simple solution for quicksort implementation.
How does it work ?
Here is an example along with visual to go with it ... (pivot)9,11,2,0
average: n log of n
worse case: n^2
The code:
items=[9,11,2,0] print(quicksort(items))
In real life, we should always use the builtin sort provided by Python. However, understanding the quicksort algorithm is instructive.
My goal here is to break down the subject such that it is easily understood and replicable by the reader without having to return to reference materials.
The quicksort algorithm is essentially the following:
If the data are randomly distributed, selecting the first data point as the pivot is equivalent to a random selection.
Readable example:
First, let's look at a readable example that uses comments and variable names to point to intermediate values:
To restate the algorithm and code demonstrated here - we move values above the pivot to the right, and values below the pivot to the left, and then pass those partitions to same function to be further sorted.
Golfed:
This can be golfed to 88 characters:
To see how we get there, first take our readable example, remove comments and docstrings, and find the pivot in-place:
Now find below and above, in-place:
Now, knowing that
and
returns the prior element if false, else if it is true, it evaluates and returns the following element, we have:Since lambdas return a single epression, and we have simplified to a single expression (even though it is getting more unreadable) we can now use a lambda:
And to reduce to our example, shorten the function and variable names to one letter, and eliminate the whitespace that isn't required.
Note that this lambda, like most code golfing, is rather bad style.
In-place Quicksort, using the Hoare Partitioning scheme
The prior implementation creates a lot of unnecessary extra lists. If we can do this in-place, we'll avoid wasting space.
The below implementation uses the Hoare partitioning scheme, which you can read more about on wikipedia (but we have apparently removed up to 4 redundant calculations per
partition()
call by using while-loop semantics instead of do-while and moving the narrowing steps to the end of the outer while loop.).Not sure if I tested it thoroughly enough:
Conclusion
This algorithm is frequently taught in computer science courses and asked for on job interviews. It helps us think about recursion and divide-and-conquer.
Quicksort is not very practical in Python since our builtin timsort algorithm is quite efficient, and we have recursion limits. We would expect to sort lists in-place with
list.sort
or create new sorted lists withsorted
- both of which take akey
andreverse
argument.I think both answers here works ok for the list provided (which answer the original question), but would breaks if an array containing non unique values is passed. So for completeness, I would just point out the small error in each and explain how to fix them.
For example trying to sort the following array [12,4,5,6,7,3,1,15,1] (Note that 1 appears twice) with Brionius algorithm .. at some point will end up with the less array empty and the equal array with a pair of values (1,1) that can not be separated in the next iteration and the len() > 1...hence you'll end up with an infinite loop
You can fix it by either returning array if less is empty or better by not calling sort in your equal array, as in zangw answer
The fancier solution also breaks, but for a different cause, it is missing the return clause in the recursion line, which will cause at some point to return None and try to append it to a list ....
To fix it just add a return to that line