{"id":240,"date":"2026-11-13T12:35:37","date_gmt":"2026-11-13T04:35:37","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-quickselect-finds-one-order-statistic\/"},"modified":"2026-11-13T21:53:28","modified_gmt":"2026-11-13T13:53:28","slug":"how-quickselect-finds-one-order-statistic","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-quickselect-finds-one-order-statistic\/","title":{"rendered":"How quickselect finds one order statistic"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> <strong>Quickselect<\/strong> partitions around a pivot and recurses into the only side that still contains rank k. A partition that places the pivot at its final index answers immediately when that index equals k. The expected cost with a random pivot is <strong>\u0398(n)<\/strong>. A pivot that always leaves k on a side of length n\u22121 costs <strong>\u0398(n\u00b2)<\/strong>. The algorithm returns one order statistic, not a sorted array.<\/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\">The k-th smallest key is the key that would sit at index k after a full sort, counting from zero. Sorting computes every other rank as well. After a partition, the pivot&#8217;s final index p is its rank. If p = k the pivot is the answer. If k &lt; p every key at or to the right of p is too large, and the answer lies in the left slice. Otherwise it lies in the right slice.<\/p>\n\n\n<p class=\"wp-block-paragraph\">That discard needs a partition that actually places the pivot. Hoare&#8217;s partition returns a cut, and the pivot value may sit on either side of the cut, so the rank test p = k is not available.<\/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\">With a uniformly random pivot, the expected number of comparisons is linear in n. A standard bound is at most 4n for the average over pivots, up to lower-order terms; the exact constant depends on the partition. The worst case remains \u0398(n\u00b2), the same one-sided recursion as quicksort. Extra memory is the recursion stack, which can be held to O(log n) expected by iterating and, if desired, recursing in a way that does not stack both sides. Only one side exists here, so the loop is naturally iterative.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The result is the key of rank k, and the array is rearranged so that every index below the final pivot position holds a key \u2264 that key. The order inside each side is otherwise unspecified. Equal keys make the rank any index of that key&#8217;s run, depending on how the partition buckets equals.<\/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>Ask for rank k with 0 \u2264 k &lt; n. Shuffle the array, or choose a random pivot index at each step.<\/li>\n<li>Partition so the chosen pivot ends at an index p, with keys before p \u2264 the pivot and keys after p \u2265 the pivot. Lomuto&#8217;s partition does this. Hoare&#8217;s cut does not.<\/li>\n<li>If p = k, return the pivot. If k &lt; p, repeat on [lo, p). Otherwise repeat on (p, hi].<\/li>\n<li>A median-of-three pivot reduces the chance of a one-sided split and does not by itself turn the worst case into a linear bound.<\/li>\n<li>When a hard linear worst case is required, choose the pivot with median of medians instead of at random.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">Expected linear time selects one rank. It does not sort. Calling quickselect once per rank reintroduces an n log n sort with a worse constant. A worst-case linear selection is median of medians, which is this recursion with a more expensive pivot.<\/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 pivot is not placed at its rank<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Hoare&#8217;s partition, then test the cut index against k<\/td>\n<td>The cut is not the pivot&#8217;s rank. The answer can lie on either side, and excluding the cut drops a candidate.<\/td>\n<\/tr>\n<tr>\n<td>Sort the array and index it<\/td>\n<td>The k-th key comes back, after \u0398(n log n) work. The partition discards a side so that those keys are never sorted.<\/td>\n<\/tr>\n<tr>\n<td>A fixed end pivot on a sorted array<\/td>\n<td>Each partition removes one item. Selecting the median then copies n\u00b2\/4 comparisons.<\/td>\n<\/tr>\n<tr>\n<td>Assume the expected linear bound is a deadline<\/td>\n<td>An adversary who sees the pivot rule can force the long side to contain k every time. Randomness, or median of medians, is what blocks that adversary.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">Worst-case linear selection belongs to median of medians. A full ordering belongs to a sort. The partition primitive is the same one quicksort uses, and only the placed-pivot form serves this rank test.<\/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 quickselect with a partition that places the pivot. They return the element of rank 3 in zero-based order, which is <code>4<\/code>.<\/p>\n\n<pre><code class=\"language-bash\">a=(7 2 1 8 6 3 5 4)\nk=3\nlo=0\nhi=${#a[@]}\nwhile (( hi - lo &gt; 1 )); 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 == k )); then break; fi\n  if (( k &lt; i )); then hi=$i; else lo=$((i+1)); fi\ndone\necho &quot;${a[k]}&quot;\n<\/code><\/pre>\n<pre><code class=\"language-python\">def quickselect(a, k):\n    a = a[:]\n    lo, hi = 0, len(a)\n    while hi - lo &gt; 1:\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 == k:\n            return a[i]\n        if k &lt; i:\n            hi = i\n        else:\n            lo = i + 1\n    return a[lo]\n\ndata = [7, 2, 1, 8, 6, 3, 5, 4]\nassert quickselect(data, 3) == sorted(data)[3] == 4\nprint(quickselect(data, 3))\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>nth_element<\/code><\/strong> and database percentiles use quickselect, or introselect wrapped around it, to find one order statistic without sorting the rest. A median filter and a top-k threshold are the same call. A full sort is wasted work when only the k-th key is required.<\/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 quickselect when the worst case must be linear. Median of medians pays a large constant for that proof. Drop it when every rank is needed. A sort is then simpler. Keep random-pivot quickselect when one order statistic is required and an expected linear scan of the array is the right budget.<\/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 quickselect returns the placed pivot and the expected linear cost of following only the side that holds rank k. <strong>Quickselect partitions until the pivot lands on the requested rank, which takes expected linear time and can take quadratic time if the pivot is always at the end.<\/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: Quickselect partitions around a pivot and recurses into the only side that still contains rank k. A partition that places the pivot at its final index answers immediately when that index equals k. The expected cost with a random pivot is \u0398(n). A pivot that always leaves&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,43],"tags":[],"class_list":["post-240","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-searching"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/240","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=240"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/240\/revisions"}],"predecessor-version":[{"id":639,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/240\/revisions\/639"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=240"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=240"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=240"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}