IntroSort

Starts as quicksort, switches to heapsort if recursion gets too deep, and insertion sort for small partitions. Used by C++ STL.

Best O(n log n) Avg O(n log n) Worst O(n log n) Space O(log n) Stable No In-place Yes Comparison-based

How it works

Starts as quicksort, switches to heapsort if recursion gets too deep, and insertion sort for small partitions. Used by C++ STL.

Implementation

function introSort(arr) {
  const maxDepth = Math.floor(2 * Math.log2(arr.length));
  function rec(lo, hi, depth) {
    if (hi - lo < 16) { insertionSort(arr, lo, hi); return; }
    if (depth === 0) { heapSort(arr, lo, hi); return; }
    const pivot = medianOfThree(arr, lo, hi);
    const pi = partition(arr, lo, hi, pivot);
    rec(lo, pi - 1, depth - 1);
    rec(pi + 1, hi, depth - 1);
  }
  rec(0, arr.length - 1, maxDepth);
}