{"id":241,"date":"2026-11-13T12:35:38","date_gmt":"2026-11-13T04:35:38","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-quicksort-recurses-after-a-partition\/"},"modified":"2026-11-13T21:53:30","modified_gmt":"2026-11-13T13:53:30","slug":"how-quicksort-recurses-after-a-partition","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-quicksort-recurses-after-a-partition\/","title":{"rendered":"How quicksort recurses after a partition"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Quicksort<\/strong> partitions a slice around a pivot and sorts the two sides. With <strong>Lomuto&#8217;s partition<\/strong> the pivot ends at its final index and is excluded from both recursive calls. With <strong>Hoare&#8217;s partition<\/strong> the cut index is only a boundary between small keys and large keys, and the pivot may sit on either side of it. Average cost with a random pivot is <strong>O(n log n)<\/strong>. A consistently bad pivot is <strong>\u0398(n\u00b2)<\/strong>.<\/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\">Partition rearranges a slice so that keys on the left of a cut are at most the pivot and keys on the right are at least the pivot. The recursive calls are then independent. Which index is passed to those calls depends on which partition was used. Treating Hoare&#8217;s returned index as the pivot&#8217;s final home drops keys or loops.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The pivot also decides the cost. A pivot that always lands at the end of the slice leaves one side empty and the other side only one item shorter. That recursion is \u0398(n\u00b2). A pivot near the middle splits the work into the same recurrence as mergesort.<\/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\">After a correct partition, each side is a smaller independent sort. Random pivots give an expected O(n log n) comparisons; the constant for a uniformly random pivot is about 1.386 n log\u2082 n. The worst case is \u0398(n\u00b2). Extra memory is the recursion stack. Recursing into the smaller side first, and looping on the larger side, keeps that stack at O(log n) even on a bad split. The usual in-place partitions are unstable.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Lomuto walks one index and swaps keys greater than the pivot to the right. When it finishes, the pivot occupies its final rank and both sides exclude that index. Hoare walks two indices inward and swaps a large left key with a small right key. When they cross, every key up through the crossing is at most every key after it, and the pivot value itself need not sit at the crossing.<\/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>On a slice of fewer than two items, return.<\/li>\n<li>Choose a pivot. A random index, or a median of the first, middle, and last items, avoids the sorted-input degeneration of always picking one end.<\/li>\n<li>Lomuto: swap the pivot to the end, scan the slice, swap each smaller key into the growing left part, then swap the pivot into the boundary. Recurse on the two open sides and skip the pivot index.<\/li>\n<li>Hoare: scan from both ends, swap inversions relative to the pivot value, and stop when the indices cross. Recurse on the left slice through the crossing and the right slice after it. Include every index in exactly one side.<\/li>\n<li>Sort the smaller side first, then continue with the larger side in the same frame, so the stack depth tracks the smaller side.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">This is an in-place comparison sort. It does not provide a stable order, and the O(n log n) figure is an expectation unless the recursion is capped and a heap finishes the deep slices. That cap is introsort.<\/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 partition&#8217;s cut is misread<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Exclude Hoare&#8217;s cut index as if the pivot were finished<\/td>\n<td>The pivot may lie strictly inside one side. Dropping the cut index loses an unsorted key, and a side that does not shrink loops.<\/td>\n<\/tr>\n<tr>\n<td>Always pivot on the first item<\/td>\n<td>A sorted or nearly sorted array produces empty sides. The cost becomes \u0398(n\u00b2) on the input people try first.<\/td>\n<\/tr>\n<tr>\n<td>Assume the average bound is a worst-case bound<\/td>\n<td>Adversarial or already ordered pivots realize the quadratic recursion. The expectation needs random pivots or an equivalent shuffle.<\/td>\n<\/tr>\n<tr>\n<td>Partition equals to both sides at random and call the sort stable<\/td>\n<td>Equal keys are swapped across the pivot. Their original order is gone.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A hard O(n log n) ceiling on the same partition belongs to introsort. A stable n log n sort belongs to mergesort. Finding one rank, rather than sorting, is quickselect and reuses a partition that places the pivot.<\/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\">The Bash script and the Python script quicksort with Lomuto&#8217;s partition, then finish the smaller side before the larger side. Both print <code>1 2 3 4 4<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(4 2 4 3 1)\nrec() {\n  local lo=$1 hi=$2 pivot i j t\n  while (( hi - lo &gt;= 2 )); do\n    pivot=${a[hi-1]}\n    i=$lo\n    for ((j=lo; j&lt;hi-1; j++)); do\n      if (( a[j] &lt; pivot )); then\n        t=${a[i]}; a[i]=${a[j]}; a[j]=$t\n        i=$((i+1))\n      fi\n    done\n    t=${a[i]}; a[i]=${a[hi-1]}; a[hi-1]=$t\n    if (( i - lo &lt; hi - (i + 1) )); then\n      rec &quot;$lo&quot; &quot;$i&quot;\n      lo=$((i+1))\n    else\n      rec &quot;$((i+1))&quot; &quot;$hi&quot;\n      hi=$i\n    fi\n  done\n}\nrec 0 ${#a[@]}\necho &quot;${a[*]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def quicksort(a):\n    def rec(lo, hi):\n        while hi - lo &gt;= 2:\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            if i - lo &lt; hi - (i + 1):\n                rec(lo, i)\n                lo = i + 1\n            else:\n                rec(i + 1, hi)\n                hi = i\n    rec(0, len(a))\n    return a\n\na = quicksort([4, 2, 4, 3, 1])\nassert a == sorted([4, 2, 4, 3, 1])\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\">Quicksort is the partition sort inside <strong>introsort<\/strong> and the historical implementation of C <code>qsort<\/code>. The average bound is n log n; a bad pivot makes it quadratic, which is why the production sort caps the depth with a heap. A stable sort does not use this partition.<\/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 plain quicksort when the caller needs a worst-case n log n proof or a stable result. Use introsort for the first and mergesort or timsort for the second. Keep quicksort when average speed and an in-place partition are the requirements, and when the pivot is random or otherwise kept off the end of a sorted slice.<\/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 quicksort returns the difference between a partition that places the pivot and a partition that only returns a cut. <strong>Quicksort&#8217;s average cost is n log n with a random pivot, and Hoare&#8217;s cut is a boundary the pivot may sit on either side of.<\/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: Quicksort partitions a slice around a pivot and sorts the two sides. With Lomuto&#8217;s partition the pivot ends at its final index and is excluded from both recursive calls. With Hoare&#8217;s partition the cut index is only a boundary between small keys and large keys, and the&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-241","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\/241","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=241"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/241\/revisions"}],"predecessor-version":[{"id":640,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/241\/revisions\/640"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=241"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=241"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=241"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}