Learning Erlang: The Beautiful Quicksort

Sometimes you really have to stop and contemplate how beautiful code is. This is an erlang quicksort algorithm, one of the most efficient (if I remember correctly it’s the most efficient) sorting algorithms. I still remember the pains of implementing it in C.

qsort([]) -> [];
qsort([Pivot|T]) ->
	qsort([X || X <- T, X =< Pivot])
	++ [Pivot] ++
	qsort([X || X <- T, X > Pivot]).

Short + Clean + Elegant = Beautiful.

8 Responses to “Learning Erlang: The Beautiful Quicksort”

  1. tom Says:

    blanket statements are usually wrong :)

    ‘the most efficient’ in certain circumstances ;)

  2. Giovanni Intini Says:

    Then I almost remembered correctly :D

    Do you remember what’s the least efficient order for quicksort? The reverse ordered array?

  3. fullo Says:

    as I said saturday erLang seems to me very similar to prolog :)

    partition([], _, [], []).
    partition([X|Xs], Pivot, Smalls, Bigs) :-
    ( X @
    Smalls = [X|Rest],
    partition(Xs, Pivot, Rest, Bigs)
    ; Bigs = [X|Rest],
    partition(Xs, Pivot, Smalls, Rest)
    ).

    quicksort([]) —> [].
    quicksort([X|Xs])—>
    { partition(Xs, X, Smaller, Bigger) },
    quicksort(Smaller),
    [X],
    quicksort(Bigger).

    via wikipedia

  4. Giovanni Intini Says:

    It’s 14 against 5. That’s no prolog if you ask me :)

  5. riffraff Says:

    I agree it is prolog-like, it’s just that prolog lacks list comprehensions :)

    Yet, I think the prolog version could be shortened, if you consider that partition or an equivalent could be builtin it becomes two-liner (or five if you split on commas)

  6. Giovanni Intini Says:

    Omg, I’m among a group of prolog advocates :)

  7. thor Says:

    One thing should be noted: C version of quicksort sorts array _in_place_. So, yes, Erlang and Haskell versions of quicksort will look cleaner and simpler, but complexity of C code has its roots – efficiency.

  8. Giovanni Intini Says:

    It’s obvious C is more efficient, but most of the times you can give up some cycles for simpler and quicker programming.

    CPU Time costs much less than programmers’ time.