man ruby/sorting

How Ruby sorts: qsort_r, a private introsort and quickselect

lib / Ruby 9 mindraft

checked against: CRuby 4.0.10

Which algorithm runs when you call sort in Ruby, and is it stable?

people.sort { |a, b| a.age <=> b.age }
people.sort_by(&:age)
people.max_by(3, &:age)

The three lines above run three different pieces of code. This article reads them in the C source of ruby 4.0.10 (array.c, enum.c and util.c) and checks them with small programs on an Apple M2 Pro running macOS, where ruby is Homebrew’s /opt/homebrew/opt/ruby/bin/ruby 4.0.10.

The short version

  • Array#sort and sort! call ruby_qsort. On macOS and on glibc systems that is the C library’s qsort_r. Ruby only has its own quicksort as a fallback for platforms without one.
  • sort_by computes all keys first. If every key is an Integer or a Float and <=> hasn’t been redefined, it sorts them with an introsort written in enum.c (since Ruby 3.3). Otherwise it also calls ruby_qsort.
  • max_by(n), min_by(n), max(n) and min(n) don’t sort the input. They run a quickselect over a small buffer.

The documentation of sort and sort_by says the order of equal elements is “indeterminate and may be unstable”. max_by says nothing about ties.

Array#sort is the C library’s sort

rb_ary_sort duplicates the array and calls rb_ary_sort_bang, which does this:

ruby_qsort(ptr, len, sizeof(VALUE),
           rb_block_given_p()?sort_1:sort_2, &data);

sort_1 yields both elements to your block. sort_2 is the comparison without a block, and it has fast paths. Two Integers small enough to be stored inline (Fixnums) are compared as C longs, two Strings with rb_str_cmp, Floats with rb_float_cmp. Each fast path applies only while the matching <=> is still the built-in one (CMP_OPTIMIZABLE). Everything else calls <=> as a method.

What is ruby_qsort? include/ruby/util.h answers on glibc:

#ifdef HAVE_GNU_QSORT_R
# define ruby_qsort qsort_r

util.c covers BSD-style qsort_r (macOS) with a thin wrapper that reorders the arguments, and Windows with qsort_s. configure.ac tests which of the two qsort_r signatures the C library has. The installed Homebrew build says it found the BSD one, and the library imports it:

$ grep QSORT /opt/homebrew/opt/ruby/include/ruby-4.0.0/arm64-darwin27/ruby/config.h
#define HAVE_QSORT_R 1
#define HAVE_BSD_QSORT_R 1
$ nm -u /opt/homebrew/opt/ruby/lib/libruby.dylib | grep qsort
_qsort
_qsort_r

So on this Mac, [3, 1, 2].sort runs Apple’s qsort_r, and on a glibc system it runs glibc’s. What those two do is a story of its own; I wrote it up in qsort is not always quicksort.

Only when neither exists does Ruby compile its own ruby_qsort. That one is “qs6”, a quicksort whose header credits Tomoyuki Kawamura, dated 1995.4.21. It picks a median of three, or a median of three medians for 200 or more elements. For arrays of 63 or more, when its first three samples are in order, it checks once whether the whole range is already ascending, or descending, which it then reverses.

A block runs once per comparison

Because the block is the comparison function, sort with a block calls it O(n log n) times. sort_by calls its block once per element:

nums = (1..10_000).to_a.shuffle(random: Random.new(1))

calls = 0
nums.sort { |a, b| calls += 1; b <=> a }
puts "sort { |a, b| b <=> a }: #{calls} block calls"

calls = 0
nums.sort_by { |n| calls += 1; -n }
puts "sort_by { |n| -n }:      #{calls} block calls"

calls = 0
nums.max_by(3) { |n| calls += 1; n }
puts "max_by(3) { |n| n }:     #{calls} block calls"
$ ruby sortcalls.rb
sort { |a, b| b <=> a }: 134530 block calls
sort_by { |n| -n }:      10000 block calls
max_by(3) { |n| n }:     10000 block calls

10,000 × log₂ 10,000 is about 132,900, so Apple’s qsort_r makes close to n log₂ n comparisons here.

sort_by: keys first, then a sort

The sort_by documentation calls itself a Schwartzian transform, and shows the hand-written version: map each element to [key, element], sort, map back. The C code does the same thing without creating those little arrays.

For an Array receiver, enum_sort_by allocates one hidden array of 2n slots. sort_by_i runs your block and writes the key and the element into a 32-slot buffer (SORT_BY_BUFSIZE is 16 pairs), which is appended to the big array each time it fills. The result is a flat run of alternating keys and elements:

[ key0, elem0, key1, elem1, key2, elem2, ... ]

The sort treats each pair of slots as one 16-byte record. Afterwards a loop copies every second slot to the front, and the array shrinks to n and gets its class back.

While the block runs, sort_by_i also tracks whether every key so far is a Fixnum or a Float (primitive_uniformed). If so, and <=> is untouched for both, the records go to rb_uniform_intro_sort_2. Otherwise they go to ruby_qsort with sort_by_cmp, which uses the same comparison fast paths as sort.

The introsort in enum.c

rb_uniform_intro_sort_2 first walks the keys once. If they are already in order, it returns. Otherwise it calls rb_uniform_quicksort_intro_2 with a depth budget of 2 × ⌊log₂ n⌋:

  • a range of 16 records or fewer gets an insertion sort;
  • a range that runs out of depth budget gets a heapsort;
  • everything else is partitioned around the median of the first, middle and last keys, and both sides recurse.

Comparisons are inline C. Two Fixnums compare as signed machine words. Mixed Fixnum and Float keys go through rb_float_cmp. No Ruby method is called.

You can see the switch. If I prepend a module that counts calls to Integer#<=>, the “untouched” condition fails, and the same sort_by falls back to qsort_r and calls the method:

nums = (1..10_000).to_a.shuffle(random: Random.new(1))

$calls = 0
module CountingCompare
  def <=>(other)
    $calls += 1
    super
  end
end
Integer.prepend(CountingCompare)

nums.sort_by { |n| -n }
puts "sort_by after redefining Integer#<=>: #{$calls} calls"
$calls = 0
nums.sort
puts "sort after redefining Integer#<=>:    #{$calls} calls"
$ ruby redefine.rb
sort_by after redefining Integer#<=>: 134530 calls
sort after redefining Integer#<=>:    134219 calls

sort_by { |n| -n } made exactly as many comparisons as the earlier sort { |a, b| b <=> a }. Both sorted the same 10,000 numbers into the same order with the same qsort_r.

Stability, measured

None of these promise stability, so I checked what they do on this Mac, where the qsort_r paths run Apple’s qsort_r. Forty records keyed 0 to 3; “stable” means the records with the same key keep their input order:

recs = (1..40).map { |i| [i % 4, i] }
stable = ->(sorted) { sorted.chunk_while { |a, b| a[0] == b[0] }.all? { |run| run.map(&:last) == run.map(&:last).sort } }
puts "sort_by, Integer keys: #{stable.(recs.sort_by(&:first))}"
puts "sort_by, String keys:  #{stable.(recs.sort_by { |r| r[0].to_s })}"
puts "sort with a block:     #{stable.(recs.sort { |a, b| a[0] <=> b[0] })}"
puts "sort_by.with_index:    #{stable.(recs.sort_by.with_index { |r, i| [r[0], i] })}"
small = (1..16).map { |i| [i % 4, i] }
puts "sort_by, 16 elements:  #{stable.(small.sort_by(&:first))}"
$ ruby stable.rb
sort_by, Integer keys: false
sort_by, String keys:  false
sort with a block:     false
sort_by.with_index:    true
sort_by, 16 elements:  true

The introsort, qsort_r with a block and qsort_r through sort_by all reorder equal keys here. On glibc the two qsort_r rows could come out differently, since its qsort_r is a merge sort; I didn’t run this there. With 16 records or fewer the integer path is a plain insertion sort, which happens to be stable. So a test with a short array passes, and a longer one may not. The reliable fix is to make ties impossible. sort_by.with_index { |x, i| [key, i] } uses the original position as a second key. Its keys are Arrays, so it takes the qsort_r path with Array#<=>.

max_by(n): a quickselect, not a sort

max_by(n), min_by(n), max(n) and min(n) all end in rb_nmin_run in enum.c. It keeps a buffer of 4n entries (key and element side by side, as in sort_by). For max_by(3) that is 12. Each new element:

  1. gets its key from the block;
  2. is dropped at once if a threshold exists and the key doesn’t beat it;
  3. otherwise goes into the buffer.

When the buffer is full, nmin_filter runs a quickselect that puts the best n entries in front and gathers entries equal to the pivot together. It keeps those n, and remembers the last pivot as the new threshold. At the end it filters once more and sorts the n survivors with ruby_qsort, reversing them for the max variants, so the result comes back best first. That makes the cost O(k) for k elements plus a sort of n, and the block still runs exactly once per element, as the counts above show.

Two edge cases from the source: max_by(0) returns [] without looking at anything, and a negative n raises ArgumentError (“negative size (-1)”).

Curious facts

  • The sort_by documentation still shows a benchmark in which sorting 100,000 random integers takes 0.18 s with sort and 2.01 s with sort_by { |a| a }. Its own example on ruby 4.0.10:

    $ ruby docbench.rb
                     user     system      total        real
    Sort         0.008705   0.000089   0.008794 (  0.008793)
    Sort by      0.008914   0.000058   0.008972 (  0.008983)
    

    Both take about 9 ms here.

  • sort_by raises “sort_by reentered” if your block manages to call back into the same sort. It checks for that both while collecting keys and during comparisons.

  • Array#sort! sorts a hidden copy of the array and checks the receiver after every comparison that ran Ruby code. Freezing the array from inside the block raises an error:

    $ ruby -e 'a = [3, 1, 2]; begin; a.sort! { |x, y| a.freeze; x <=> y }; rescue => e; p e; end'
    #<FrozenError: array frozen during sort>
    
  • The documented way to sort descending is sort_by { ... }.reverse!. For numeric keys sort_by { |x| -x } gives the same order, up to ties, in one pass, and still takes the introsort, because the negated keys are still Integers.

History

  • 1995: the date in the header of the qs6 quicksort in util.c.
  • 2.2: min, min_by, max and max_by accept a count (NEWS-2.2.0).
  • 2.3: util.c starts calling the C library’s qsort_r (no qsort_r in util.c at v2_2_0, a BSD wrapper at v2_3_0).
  • 3.3: the numeric introsort for sort_by appears in enum.c (rb_uniform_intro_sort_2 is absent at v3_2_0 and present at v3_3_0).

Sources

All source links are at tag v4.0.10 (commit a704b7cd95), the build that printed ruby 4.0.10 (2026-11-19 revision a704b7cd95) +PRISM [arm64-darwin27].

ls ruby/