man elixir/sorting

How Elixir sorts: Enum.sort_by and lists:sort

lib / Elixir 8 mindraft

checked against: Elixir 1.20.5, Erlang/OTP 29.1.3

What does Elixir actually run when you sort, and is it stable?

words
|> Enum.frequencies()
|> Enum.sort_by(fn {_word, n} -> n end, :desc)
|> Enum.take(10)

Elixir has no sorting algorithm of its own for lists. Enum.sort and Enum.sort_by prepare the data and call Erlang’s lists module from the standard library, and lists:sort is a merge sort written in Erlang, not C. This article reads enum.ex and list.ex at Elixir v1.20.5 and lists.erl at OTP-29.1.3, and checks them with small scripts on an Apple M2 Pro running Elixir 1.20.5 on Erlang/OTP 29.1.3.

The short version

  • Enum.sort/1 on a list is :lists.sort/1. Enum.sort/2 with a function is :lists.sort/2. :desc on a list is :lists.sort/1 followed by :lists.reverse/1.
  • Enum.sort_by/3 pairs every element with its key, sorts the pairs with :lists.keysort/2, and drops the keys. Your function runs once per element, and with :asc or :desc the sort itself compares the keys with the VM’s built-in term order, without calling any Elixir function.
  • lists:sort is a stable natural merge sort: it first cuts the input into runs that are already in order, then merges them. Sorted or reverse-sorted input costs n − 1 comparisons.

The call chain

Here is sort/2 for lists:

def sort(enumerable, sorter) when is_list(enumerable) do
  case sorter do
    :asc -> :lists.sort(enumerable)
    :desc -> :lists.sort(enumerable) |> :lists.reverse()
    _ -> :lists.sort(to_sort_fun(sorter), enumerable)
  end
end

And sort_by/3:

def sort_by(enumerable, mapper, :desc) when is_function(mapper, 1) do
  enumerable
  |> reduce([], &[{&1, mapper.(&1)} | &2])
  |> List.keysort(1, :asc)
  |> List.foldl([], &[elem(&1, 0) | &2])
end

def sort_by(enumerable, mapper, sorter) when is_function(mapper, 1) do
  enumerable
  |> map(&{&1, mapper.(&1)})
  |> List.keysort(1, sorter)
  |> map(&elem(&1, 0))
end

List.keysort(list, 1, :asc) is :lists.keysort(2, list), because Erlang counts tuple positions from 1. Any other sorter goes to :lists.sort/2 with a closure that pulls the key out of each tuple and applies your comparison.

The :desc clause is the clever one. reduce with [... | &2] builds the decorated list backwards, so equal keys are now in reverse input order. keysort sorts ascending and, being stable, keeps them that way. Then foldl with [... | &2] reverses the whole list. The keys end up descending, and the elements with equal keys end up back in input order. One stable ascending sort between two reversals gives a stable descending sort, and no comparison function is involved.

Counting calls

A comparison function runs once per comparison. A sort_by mapper runs once per element. I counted both with :counters:

:rand.seed(:exsss, {1, 2, 3})
shuffled = Enum.shuffle(1..10_000)
c = :counters.new(1, [])
count = fn list, label ->
  :counters.put(c, 1, 0)
  Enum.sort(list, fn a, b -> :counters.add(c, 1, 1); a <= b end)
  IO.puts("#{label}: #{:counters.get(c, 1)} comparisons")
end
count.(shuffled, "sort/2, 10,000 shuffled")
count.(Enum.to_list(1..10_000), "sort/2, 10,000 ascending")
count.(Enum.to_list(10_000..1//-1), "sort/2, 10,000 descending")
:counters.put(c, 1, 0)
Enum.sort_by(shuffled, fn x -> :counters.add(c, 1, 1); x end, :desc)
IO.puts("sort_by/3 :desc, 10,000 shuffled: #{:counters.get(c, 1)} mapper calls")
:counters.put(c, 1, 0)
Enum.sort_by(shuffled, fn x -> :counters.add(c, 1, 1); x end, fn a, b -> :counters.add(c, 1, 1); a >= b end)
IO.puts("sort_by/3 with a sorter fn: #{:counters.get(c, 1)} mapper + sorter calls")
$ elixir sort2.exs
sort/2, 10,000 shuffled: 128496 comparisons
sort/2, 10,000 ascending: 9999 comparisons
sort/2, 10,000 descending: 9999 comparisons
sort_by/3 :desc, 10,000 shuffled: 10000 mapper calls
sort_by/3 with a sorter fn: 138496 mapper + sorter calls

128,496 comparisons for 10,000 shuffled numbers, close to n log₂ n (132,877). Already sorted input in either direction takes 9,999. With :desc, sort_by calls the mapper 10,000 times and nothing else. With a custom sorter it calls the mapper 10,000 times and the sorter 128,496 times, the same comparisons as sort/2.

Inside lists:sort

The sort functions sit at the end of lists.erl, under a comment that says they “used to be in their own module (lists_sort)”. sort/1 starts by looking at the first two elements. If they are in order it calls split_1, which keeps extending an ascending run:

split_1(X, Y, [Z | L], R, Rs) when Z >= Y ->
    split_1(Y, Z, L, [X | R], Rs);
split_1(X, Y, [Z | L], R, Rs) when Z >= X ->
    split_1(Z, Y, L, [X | R], Rs);
split_1(X, Y, [Z | L], [], Rs) ->
    split_1(X, Y, L, [Z], Rs);
split_1(X, Y, [Z | L], R, Rs) ->
    split_1_1(X, Y, L, R, Rs, Z);

X and Y are the two largest elements of the run so far. An element at least as big as Y extends the run. One that falls between X and Y is taken too: it takes X’s place next to Y, and X joins the rest of the run. An element smaller than both is set aside (split_1_1), and the run ends only when the next misfit arrives; the two misfits start the next run. split_2 does the same for descending runs. fsplit_1 and fsplit_2 do the same through the comparison function, which is why sorted and reverse-sorted input cost 9,999 calls above.

Then mergel and rmergel merge the runs, three at a time:

mergel([[_|_]=T1, [H2 | T2], [H3 | T3] | L], Acc) ->
    mergel(L, [merge3_1(T1, [], H2, T2, H3, T3) | Acc]);

Erlang lists are singly linked and are built by adding to the front, so a merge naturally produces its output backwards. Instead of reversing after every merge, the code alternates: mergel merges ascending lists into descending results, and rmergel merges those back into ascending ones. keysort has the same structure in keysplit_1 and keymergel, comparing element(N, Tuple) instead of whole terms.

sort/2, with a function, is different. fsplit_1 finds runs the same way but calls Fun(A, B) for every test, and fmergel merges two lists at a time:

fmergel([T1, [H2 | T2] | L], Acc, Fun, asc) ->
    fmergel(L, [fmerge2_1(T1, H2, Fun, T2, []) | Acc], Fun, asc);

So the built-in versions skip the closure calls and also do fewer merge passes.

Stability, and the one place it breaks

The lists:sort/1 documentation says “The sort is stable”, and so does lists:keysort/2’s. Elixir’s docs for Enum.sort/2 add that a sort with a function is stable “as long as the given function returns true for values considered equal”, so &<=/2 and &>=/2 are stable while &</2 and &>/2 are not. Here it is on pairs with tied counts:

pairs = [a: 1, b: 2, c: 1, d: 2]
IO.inspect(Enum.sort_by(pairs, &elem(&1, 1), :desc), label: "sort_by :desc")
IO.inspect(Enum.sort(pairs, &(elem(&1, 1) >= elem(&2, 1))), label: "sort >=")
IO.inspect(Enum.sort(pairs, &(elem(&1, 1) > elem(&2, 1))), label: "sort >")
$ elixir sort1.exs
sort_by :desc: [b: 2, d: 2, a: 1, c: 1]
sort >=: [b: 2, d: 2, a: 1, c: 1]
sort >: [d: 2, b: 2, c: 1, a: 1]

With > every tie came out reversed. The docs call :desc “a convenience for &>=/2”, but on a list it is implemented as an ascending sort followed by a reverse, and the reverse flips ties. Integers and floats that compare equal show it:

IO.inspect(Enum.sort([1, 1.0], :desc), label: "Enum.sort(:desc)     ")
IO.inspect(Enum.sort([1, 1.0], &>=/2), label: "Enum.sort(&>=/2)     ")
IO.inspect(Enum.sort_by([1, 1.0], & &1, :desc), label: "Enum.sort_by(:desc)  ")
$ elixir sort3.exs
Enum.sort(:desc)     : [1.0, 1]
Enum.sort(&>=/2)     : [1, 1.0]
Enum.sort_by(:desc)  : [1, 1.0]

sort_by with :desc keeps the input order, thanks to its two reversals. Enum.sort(list, :desc) does not.

Term ordering: sorting without a function

lists:sort/1 needs no comparison function because every term on the BEAM has a place in one global order. Elixir’s Kernel docs give it as:

number < atom < reference < function < port < pid < tuple < map < list < bitstring
Enum.sort([{1}, "b", :a, [1], %{}, 2.0, 1, self()])
# [1, 2.0, :a, #PID<0.94.0>, {1}, %{}, [1], "b"]

Tuples of the same size compare element by element, which makes tuples the usual way to sort by several keys: Enum.sort_by(list, &{&1.score, &1.name}) sorts by score and then by name. In the VM, erts_cmp takes a shortcut for the most common case. When both terms are small integers it subtracts them:

} else if (is_both_small(a, b)) {
    return (signed_val(a) - signed_val(b));

The order compares structure, not meaning. The Enum.sort/2 docs warn that dates are structs, and <= on two Date structs compares their fields in alphabetical order, day before month before year. Passing a module, as in Enum.sort(dates, Date), makes Elixir call Date.compare/2 instead.

Curious facts

  • Enum.sort(list, :desc) and Enum.sort(list, &>=/2) disagree on ties: [1.0, 1] against [1, 1.0]. Enum.sort_by(list, & &1, :desc) agrees with &>=/2.
  • A sorted or reverse-sorted list of 10,000 elements costs 9,999 comparisons, because lists:sort finds runs in both directions before it merges anything.
  • The built-in sorts merge three lists at a time; the one that takes a function merges two.
  • Enum.sort/2 on something that isn’t a list, such as a map, doesn’t build a list first. It runs a port of fsplit_1’s run detection inside reduce (sort_reducer in enum.ex) and merges the runs in Elixir.
  • List.keysort/3 counts positions from 0 and :lists.keysort/2 from 1, so Elixir adds one on the way through.

History

  • Elixir v1.10.0 (2020-01-27 in its CHANGELOG) added the :asc and :desc shortcuts and module sorters such as Date to Enum.sort, and the same to Enum.sort_by, Enum.min_by, Enum.max_by and friends.
  • The sort code in lists.erl lived in its own module, lists_sort, before it was moved into lists (per the comment in lists.erl; it gives no version).

Sources

Elixir at tag v1.20.5:

Erlang/OTP at tag OTP-29.1.3: