Algorithm Visualiser by Tsvetozar Biserov

Intro Sort

  • Ω( n log n )
  • Θ( n log n )
  • O( n log n )
  • space O( log n )

This intro sort runs the same median-of-three quick sort as the quick sort page, but it counts how many partitions deep it has gone. If that count reaches twice the integer part of log₂ n, the current range is handed to heap sort. Any range of 16 elements or fewer is finished with insertion sort instead of being partitioned further.

Array
Comparator strip Index down, time to the right
100 elements
×20 steps/frame

Comparisons 1
—
Reads 2
—
Writes 2
—
Swaps 3
—
Real time 4
—
Visual time 4
—
  1. Comparisons count only element-against-element checks; loop and index checks are never counted.
  2. Reads and writes include reads and writes to helper buffers (merge, counting, radix, bucket and tim sort).
  3. A swap counts once, as a swap. It is never also counted as a read or a write.
  4. Real time is the average time of the counted sort on this device over repeated runs, measured once before playback and independent of animation speed. Visual time is the time spent animating, excluding pauses.

How intro sort works

The trace for 5, 2, 6, 1, 4, 3 contains no partitioning at all. The array has six elements, which is below the cutoff of 17, so the main loop never starts and the whole range goes straight to insertion sort. The depth limit, 2 times 2 for six elements, is 4, but it is never consulted. That is why the table lists writes rather than swaps: insertion sort holds the element being placed in a variable and shifts larger neighbours one slot to the right.

The first write is 5 into index 1, which gives 5, 5, 6, 1, 4, 3. The 5 appears twice because the 2 is held aside and its slot has not been filled yet; the next write drops it at index 0 and the array reads 2, 5, 6, 1, 4, 3. The 6 is already in place and costs no write. The 1 then has to travel to the front, shifting 6, 5 and 2 right in turn: 2, 5, 6, 6, 4, 3, then 2, 5, 5, 6, 4, 3, then 2, 2, 5, 6, 4, 3, and finally 1, 2, 5, 6, 4, 3.

The 4 shifts 6 and 5 and lands at index 2, giving 1, 2, 5, 6, 6, 3, then 1, 2, 5, 5, 6, 3, then 1, 2, 4, 5, 6, 3. The 3 shifts 6, 5 and 4 and lands at index 2, which ends at 1, 2, 3, 4, 5, 6. Altogether there were 13 writes, 12 comparisons and no swaps. On an array of 1000 elements the picture is very different: the partitioning of the quick sort page runs first, and the insertion step only ever sees pieces of at most 16 elements.

Intro Sort on 5 2 6 1 4 3, one swap or write at a time. Indexes count from 0.
Step Change Array after
1 Write 5 at index 1 5 5 6 1 4 3
2 Write 2 at index 0 2 5 6 1 4 3
3 Write 6 at index 3 2 5 6 6 4 3
4 Write 5 at index 2 2 5 5 6 4 3
5 Write 2 at index 1 2 2 5 6 4 3
6 Write 1 at index 0 1 2 5 6 4 3
7 Write 6 at index 4 1 2 5 6 6 3
8 Write 5 at index 3 1 2 5 5 6 3
9 Write 4 at index 2 1 2 4 5 6 3
10 Write 6 at index 5 1 2 4 5 6 6
11 Write 5 at index 4 1 2 4 5 5 6
12 Write 4 at index 3 1 2 4 4 5 6

12 of 13 changes shown; the rest follow the same pattern until the array is sorted.

Pseudocode

introsort(lo, hi, depth)
  if hi - lo is small
    insertion-sort a[lo .. hi]
  else if depth == 0
    heap-sort a[lo .. hi]
  else
    p = partition(lo, hi)
    introsort(lo, p - 1, depth - 1)
    introsort(p + 1, hi, depth - 1)

start with depth = 2 * floor(log2 n)

Why these complexities

While it is partitioning, the algorithm is a quick sort, so a level costs about n comparisons. The depth counter caps the number of levels along any path at 2 times the integer part of log₂ n. The quick sort phase therefore costs at most about 2n log₂ n comparisons, whatever the input. If the cap is reached, heap sort takes over the range that is left, which is at most n elements and costs O(n log n) on its own. Insertion sort on pieces of at most 16 elements adds at most 120 comparisons per piece, and the pieces together contribute only O(n). The sum is O(n log n) in the worst case.

On ordinary data the cap is never reached, and the timings follow quick sort: 11,247 comparisons for 1000 shuffled values, 6,942 for 1000 sorted ones, where the median-of-three pivot splits evenly. The best case is still n log n, because partitioning runs even when the input is ordered; only the small pieces profit from existing order. The fallback does fire in this implementation on repeated keys. The partition sends all values equal to the pivot to one side, so 1000 equal values would peel off one element per level, and after 18 levels heap sort finishes the job. That cost 20,823 comparisons, against 502,497 for the plain quick sort.

Extra memory is O(log n) for the call stack, which stays small because the code recurses into the smaller side and loops on the larger one. Heap sort and insertion sort work in place. The result is not stable, since both the partition and the heap reorder equal elements, and it is not adaptive in the sense of running much faster on ordered input.

Measured on this site

Exact counts from this site's own engine for 32 elements, using the same rules as the visualiser.

Input Comparisons Writes Swaps
Random 140 71 21
Already sorted 63 0 2
Reversed 235 211 20
Few distinct values 114 36 25

When to use it

Use it, or the library sort built on it, when you want quick sort speed with a guaranteed O(n log n) worst case and no stability requirement. It is the basis of many C++ standard library sorts.

Frequently asked questions

Why combine three algorithms?

Quick sort is fastest on typical data, heap sort guarantees the worst case, and insertion sort is best on tiny pieces.

When does it switch to heap sort?

When the recursion depth exceeds about twice log₂ n, a sign that the pivots are poor.

Is intro sort stable?

No. Quick sort partitioning and heap sort both reorder equal elements.

Does the heap sort fallback ever really run?

Yes, and not only on contrived input. In this implementation a thousand equal values reach it, because the partition puts every element equal to the pivot on the same side and each level removes only one element. After 18 levels the depth budget is gone and heap sort sorts the rest with 20,823 comparisons. Without the fallback the same input costs 502,497 comparisons.

Why stop partitioning at 16 elements?

Partitioning has fixed costs, such as picking and moving the pivot and making a recursive call, which outweigh its benefit on tiny ranges. Insertion sort has no setup and is fast on a few elements held in cache. The cutoff of 16 is a common compromise, not a law. Here each small piece is sorted on its own as soon as it appears.

Background

David Musser introduced intro sort in 1997, in a paper on introspective sorting and selection. The word fits: the algorithm watches its own behaviour, here the recursion depth, and changes strategy when the evidence says the pivots are bad. The algorithm was adopted in the SGI Standard Template Library, and the std::sort of GCC's libstdc++ descends from it, so variants of this algorithm have sorted data in a very large number of C++ programs.

The idea of falling back to a guaranteed method has been reused since. Pattern-defeating quick sort, by Orson Peters, keeps the depth-limit fallback and adds detection of ordered runs and many equal keys; the sort in Go's standard library moved to it in version 1.19. The 16-element cutoff here is a typical choice. Real libraries tune that number, and some, such as libstdc++, run a single insertion pass at the end instead of one per piece as this version does.

References

  • Musser, Introspective Sorting and Selection Algorithms, Software: Practice and Experience 27(8), 1997
  • Knuth, The Art of Computer Programming, vol. 3, section 5.2.2
  • Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms, chapters 6 and 7

Compare with

Algorithm Average time Worst time
Tim Sort Θ( n log n ) O( n log n )
Big O notation
Best time Ω( n log n ) good
Average time Θ( n log n ) good
Worst time O( n log n ) good
Worst space O( log n ) good

Properties

Stable
No
In place
Yes
Adaptive
No
Comparison-based
Yes