ArticleslgStudy

science

Introsort

Introsort is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Introsort rather than just read about it. In short: Introsort or introspective sort is a hybrid sorting algorithm that provides both fast average performance and (asymptotically) optimal worst-case performance. It begins with quicksort, it switches to heapsort when the recursion depth exceeds a level based on (the logarithm of) the number of elements being sorted and it switches to insertion sort when the number of elements is below some threshold.

Key takeaways

  • Introsort belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Introsort to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Introsort from memory before moving on to harder problems.

Reference excerpt

Introsort or introspective sort is a hybrid sorting algorithm that provides both fast average performance and (asymptotically) optimal worst-case performance. It begins with quicksort, it switches to heapsort when the recursion depth exceeds a level based on (the logarithm of) the number of elements being sorted and it switches to insertion sort when the number of elements is below some threshold. This combines the good parts of the three algorithms, with practical performance comparable to quicksort on typical data sets and worst-case O(n log n) runtime due to the heap sort. Since the three algorithms it uses are comparison sorts, it is also a comparison sort. Introsort was invented by David Musser in Musser (1997), in which he also introduced introselect, a hybrid selection algorithm based on quickselect (a variant of quicksort), which falls back to median of medians and thus provides worst-case linear complexity, which is optimal. Both algorithms were introduced with the purpose of providing generic algorithms for the C++ Standard Library which had both fast average performance and optimal worst-case performance, thus allowing the performance requirements to be tightened. Introsort is in-place and a non-stable algorithm.

Pseudocode If a heapsort implementation and partitioning functions of the type discussed in the quicksort article are available, the introsort can be described succinctly as

procedure sort(A : array): maxdepth ← ⌊log2(length(A))⌋ × 2 introsort(A, maxdepth)

procedure introsort(A, maxdepth): n ← length(A) if n < 16: insertionsort(A) else if maxdepth = 0: heapsort(A) else: p ← partition(A) // assume this function does pivot selection, p is the final position of the pivot introsort(A[1:p-1], maxdepth - 1) introsort(A[p+1:n], maxdepth - 1)

The factor 2 in the maximum depth is arbitrary; it can be tuned for practical performance. A[i:j] denotes the array slice of items i to j including both A[i] and A[j]. The indices are assumed to start with 1 (the first element of the A array is A[1]).

Analysis In quicksort, one of the critical operations is choosing the pivot: the element around which the list is partitioned. The simplest pivot selection algorithm is to take the first or the last element of the list as the pivot, causing poor behavior for the case of sorted or nearly sorted input. Niklaus Wirth's variant uses the middle element to prevent these occurrences, degenerating to O(n2) for contrived sequences. The median-of-3 pivot selection algorithm takes the median of the first, middle, and last elements of the list; however, even though this performs well on many real-world inputs, it is still possible to contrive a median-of-3 killer list that will cause dramatic slowdown of a quicksort based on this pivot selection technique. Musser reported that on a median-of-3 killer sequence of 100,000 elements, introsort's running time was 1/200 that of median-of-3 quicksort. Musser also considered the effect on caches of Sedgewick's delayed small sorting, where small ranges are sorted at the end in a single pass of insertion sort. He reported that it could double the number of cache misses, but that its performance with double-ended queues was significantly better and should be retained for template libraries, in part because the gain in other cases from doing the sorts immediately was not great.

Implementations Introsort or some variant is used in a number of standard library sort functions, including some C++ sort implementations. The June 2000 SGI C++ Standard Template Library stl_algo.h implementation of unstable sort uses the Musser introsort approach with the recursion depth to switch to heapsort passed as a parameter, median-of-3 pivot selection and the Knuth final insertion sort pass for partitions smaller than 16. The GNU Standard C++ library is similar: uses introsort with a maximum depth of 2×log2 n, followed by an insertion sort on partitions smaller than 16. LLVM libc++ also uses introsort with a maximum depth of 2×log2 n, however the size limit for insertion sort is different for different data types (30 if swaps are trivial, 6 otherwise). Also, arrays with sizes up to 5 are handled separately. Kutenin (2022) provides an overview for some changes made by LLVM, with a focus on the 2022 fix for quadraticness. The Microsoft .NET Framework Class Library, starting from version 4.5 (2012), uses introsort instead of simple quicksort. Go uses a modification of introsort: for slices of 12 or less elements it uses insertion sort, and for larger slices it uses pattern-defeating quicksort and more advanced median of three medians for pivot selection. Prior to version 1.19 it used shell sort for small slices. Java, starting from version 14 (2020), uses a hybrid sorting algorithm that uses merge sort for highly structured arrays (arrays that are composed of a small number of sorted subarrays) and introsort otherwise to sort arrays of ints, longs, floats and doubles.

Variants

pdqsort Pattern-defeating quicksort (pdqsort) is a variant of introsort developed by Orson Peters, incorporating the following improvements:

Median-of-three pivoting, "BlockQuicksort" partitioning technique to mitigate branch misprediction penalties, Linear time performance for certain input patterns (adaptive sort), Use element shuffling on bad cases before trying the slower heapsort. Improved adaptivity for low-cardinality inputs Pdqsort is used by Boost, GAP, Rust, and Zig.

fluxsort fluxsort is a stable variant of introsort incorporating the following improvements:

branchless sqrt(n) pivoting Flux partitioning technique for stable partially-in-place partitioning Significantly improved smallsort by utilizing branchless bi-directional parity merges A fallback to quadsort, a branchless bi-directional mergesort, significantly increasing adaptivity for ordered inputs Improvements introduced by fluxsort and its unstable variant, crumsort, were adopted by crumsort-rs, glidesort, ipnsort, and driftsort. The overall performance increase on random inputs compared to pdqsort is around 50%.

References

General

Worked examples

Example 1 — a first encounter with Introsort

Start with the simplest possible case. Write down what Introsort claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Introsort before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Introsort ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Introsort

In research
Introsort appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Introsort in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Introsort is common in secondary-school and first-year university syllabi. It links to neighbouring topics Comparison sorts, so understanding it makes those chapters shorter.
In everyday life
Look for Introsort outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Introsort in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Introsort means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Introsort out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Introsort in simple terms?

Introsort or introspective sort is a hybrid sorting algorithm that provides both fast average performance and (asymptotically) optimal worst-case performance. It begins with quicksort, it switches to heapsort when the recursion depth exceeds a level based on (the logarithm of) the number of element…

Why does Introsort matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Introsort?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Introsort.

Tags

  • Comparison sorts

Keep exploring