{"id":198,"date":"2026-11-13T12:34:19","date_gmt":"2026-11-13T04:34:19","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-introsort-caps-quicksort-with-a-heap\/"},"modified":"2026-11-13T21:52:34","modified_gmt":"2026-11-13T13:52:34","slug":"how-introsort-caps-quicksort-with-a-heap","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-introsort-caps-quicksort-with-a-heap\/","title":{"rendered":"How introsort caps quicksort with a heap"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Introsort<\/strong> runs quicksort until the recursion depth passes about <strong>2 log\u2082 n<\/strong>, then finishes that slice with heapsort. Short slices drop into insertion sort. The worst case becomes <strong>O(n log n)<\/strong>, the typical case keeps quicksort&#8217;s partition, and the sort stays in place and unstable. This is the usual implementation of C++ <code>std::sort<\/code>.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Quicksort&#8217;s expected cost is excellent and its worst case is quadratic. A caller of a general library sort cannot promise that the pivot sequence will be kind. Capping the depth throws the rare bad slice to an algorithm whose worst case is already n log n. The cap has to sit far enough out that random inputs almost never hit it, and close enough that a quadratic explosion cannot get far.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Small slices have the opposite problem. A partition&#8217;s setup costs more than sliding a dozen items. Those slices belong to insertion sort.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The depth limit is 2 floor(log\u2082 n), the constant Musser used. Each quicksort level does linear work, and a slice that exceeds the limit spends O(m log m) in heapsort on a slice of length m. The sum is O(n log n) on every input. Extra memory is the O(log n) recursion stack, which the depth limit makes a hard ceiling. The sort is unstable because both the partition and the heap reorder equal keys.<\/p>\n\n\n<p class=\"wp-block-paragraph\">On random data the heap is almost never entered, so the measured time tracks quicksort. On a sorted array with a naive end pivot, the heap fires and the quadratic pattern stops. That is the input the cap is for.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>If the slice length is below the insertion threshold, usually around 16, insertion-sort it and return.<\/li>\n<li>If the remaining depth allowance is 0, heapsort the slice and return.<\/li>\n<li>Partition. Lomuto&#8217;s partition places the pivot and the two recursive slices exclude it. Hoare&#8217;s partition returns a cut and both sides must cover the slice.<\/li>\n<li>Recurse on the two sides with the depth allowance decreased by one.<\/li>\n<li>The top-level call starts the allowance at 2 floor(log\u2082 n).<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The O(n log n) guarantee is for a comparison sort that may reorder equal keys. A stable sort does not become introsort by adding a depth counter. The heap is a fallback, and a correct partition is still required on the levels that have not yet fallen back.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the depth cap is treated as optional<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Quicksort with no depth cap<\/td>\n<td>A bad pivot sequence is still \u0398(n\u00b2). The cap is the difference between an expectation and a worst-case proof.<\/td>\n<\/tr>\n<tr>\n<td>Heapsort on every slice<\/td>\n<td>The worst case is fine and the typical constant and cache behavior of partitioning are thrown away. The hybrid exists to keep those on the common path.<\/td>\n<\/tr>\n<tr>\n<td>A depth limit of log\u2082 n with a poor pivot<\/td>\n<td>One-sided splits consume the allowance immediately and every slice becomes a heap. The factor 2 leaves room for ordinary unlucky pivots.<\/td>\n<\/tr>\n<tr>\n<td>Calling the result stable because insertion sort is stable<\/td>\n<td>Insertion sort runs only on tiny slices. The partitions above them have already reordered equal keys.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A stable library sort is timsort or mergesort. A pure in-place n log n sort with no quicksort path is heapsort, which introsort already calls at the cap.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment switches a quicksort slice to heapsort when the depth exceeds 2\u00b7floor(log2 n), and it insertion-sorts a slice shorter than 4. The array comes out <code>1 2 3 4 5 6<\/code>.<\/p>\n\n<pre><code class=\"language-python\">import math\n\ndef insertionsort(a, lo, hi):\n    for i in range(lo + 1, hi):\n        key = a[i]\n        j = i - 1\n        while j &gt;= lo and a[j] &gt; key:\n            a[j + 1] = a[j]\n            j -= 1\n        a[j + 1] = key\n\ndef heapsort(a, lo, hi):\n    def sift(i, end):\n        while True:\n            left, right = lo + 2 * (i - lo) + 1, lo + 2 * (i - lo) + 2\n            best = i\n            if left &lt; end and a[left] &gt; a[best]:\n                best = left\n            if right &lt; end and a[right] &gt; a[best]:\n                best = right\n            if best == i:\n                return\n            a[i], a[best] = a[best], a[i]\n            i = best\n    n = hi - lo\n    for i in range(lo + n \/\/ 2 - 1, lo - 1, -1):\n        sift(i, hi)\n    for end in range(hi - 1, lo, -1):\n        a[lo], a[end] = a[end], a[lo]\n        sift(lo, end)\n\ndef introsort(a):\n    limit = 2 * math.floor(math.log2(max(len(a), 2)))\n\n    def rec(lo, hi, depth):\n        if hi - lo &lt; 4:\n            insertionsort(a, lo, hi)\n            return\n        if depth == 0:\n            heapsort(a, lo, hi)\n            return\n        pivot = a[hi - 1]\n        i = lo\n        for j in range(lo, hi - 1):\n            if a[j] &lt; pivot:\n                a[i], a[j] = a[j], a[i]\n                i += 1\n        a[i], a[hi - 1] = a[hi - 1], a[i]\n        rec(lo, i, depth - 1)\n        rec(i + 1, hi, depth - 1)\n\n    rec(0, len(a), limit)\n\na = [3, 6, 1, 5, 2, 4]\nintrosort(a)\nassert a == [1, 2, 3, 4, 5, 6]\nprint(*a)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\"><strong>C++ <code>std::sort<\/code><\/strong> is introsort: quicksort, a depth limit, then heapsort, with insertion sort on tiny slices. That is the unstable in-place sort in production C++. A stable sort is a separate function because introsort does not keep equal elements in order.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop introsort when equal keys must keep their input order. Use timsort or mergesort. Keep it for the contract C++ <code>std::sort<\/code> publishes: an unstable in-place comparison sort with an n log n worst case and quicksort&#8217;s speed on ordinary input.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for introsort returns the depth cap that turns quicksort&#8217;s worst case into a heap. <strong>Introsort is quicksort with a 2 log n depth cap into heapsort, which makes the worst case n log n while ordinary input still partitions.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: Introsort runs quicksort until the recursion depth passes about 2 log\u2082 n, then finishes that slice with heapsort. Short slices drop into insertion sort. The worst case becomes O(n log n), the typical case keeps quicksort&#8217;s partition, and the sort stays in place and unstable. This is&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,31],"tags":[],"class_list":["post-198","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-sorting"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/198","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=198"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/198\/revisions"}],"predecessor-version":[{"id":597,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/198\/revisions\/597"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=198"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=198"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=198"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}