qsort [] = []
qsort (s:xs) = qsort [x|x <- xs,x < s] ++ [s] ++ qsort[x|x <-xs, x >= s]
I’ll admit that I’ve never really understood the QuickSort algorithm until yesterday. I’m amazed by the clarity and simplicity of the algorithm once all of the surrounding cruft is stripped away.
7 archived reader comments
Nick Guerrera (2006-06-02)
The natural recursive definition of quicksort is beautiful and simple. On the journey to discovering the full ingenuity of the algorithm, I can’t imagine anywhere else to start. However, I wouldn’t classify good pivot selection or sorting in place as “cruft”. After all, they put the “quick” in quicksort…
John Lam (2006-06-02)
No no no! I didn’t mean to say that “cruft” is not essential to a good Quicksort implementation. I just meant that it’s an impedement to understanding.
Nick Guerrera (2006-06-02)
Got it.
I think the term “cruft” is confusing in this context since it’s often used to describe code which is of poor quality or entirely redundant.
http://en.wikipedia.org/wiki/Cruft
gabriele (2006-06-10)
I still think the ruby version is mucb cleaner, even if I miss pattern matching :(
John Lam (2006/06/02)
No no no! I didn’t mean to say that "cruft" is not essential to a good Quicksort implementation. I just meant that it’s an impedement to understanding.
Nick Guerrera (2006/06/02)
Got it. I think the term "cruft" is confusing in this context since it’s often used to describe code which is of poor quality or entirely redundant. http://en.wikipedia.org/wiki/Cruft
gabriele (2006/06/10)
I still think the ruby version is mucb cleaner, even if I miss pattern matching :( <pre> def qsort(list) return [] if list.empty? x, xs = *list less, more = xs.partition{|y| y < x} qsort(less) + [x] + qsort(more) end </pre>