I’ve said it once, and I’ll say it again: in Python you can do some amazing things with little or no code at all. Sorting is also one of those things.
In poking around online, I found this little beauty that somebody had done to show how compact, elegant, and still powerfully fast one can write a Quicksort algorithm in Python:
def qsort(L): """ Porting the Erlang quicksort implementation from http://en.wikipedia.org/wiki/Erlang_(programming_language) """ if not L: return L Pivot, Tail = L[0], L[1:] return qsort([X for X in Tail if X < Pivot]) + [Pivot] + qsort([X for X in Tail if X >= Pivot]) |
Remembering back to the days of learning sorting algorithms, I recall that Quicksort was considered (at the time) one of the fastest, due in no small part to its recursive nature. It was also the bane of many an entry-level Computer Science student just digging in and getting a fuse blown out learning just what recursion meant. I even find myself going back every so often to see how rusty I’ve become with these fundamental concepts.
Looking at it now, it’s as much a piece of art as it is functional, working code.
Special thanks to the anonymous coder that put this up on Pastie.org. Link to original.