Quicksort With Median Of Three Pivot (JavaScript)
Sort an array in place using quicksort with median-of-three pivot selection to avoid worst-case behavior on already sorted or reverse sorted input.
Code
function quicksort(arr, lo = 0, hi = arr.length - 1) {
if (lo >= hi) return;
const mid = (lo + hi) >>> 1;
if (arr[mid] < arr[lo]) [arr[lo], arr[mid]] = [arr[mid], arr[lo]];
if (arr[hi] < arr[lo]) [arr[lo], arr[hi]] = [arr[hi], arr[lo]];
if (arr[mid] < arr[hi]) [arr[hi], arr[mid]] = [arr[mid], arr[hi]];
const pivot = arr[hi];
let i = lo;
for (let j = lo; j < hi; j++) {
if (arr[j] < pivot) { [arr[i], arr[j]] = [arr[j], arr[i]]; i++; }
}
[arr[i], arr[hi]] = [arr[hi], arr[i]];
quicksort(arr, lo, i - 1);
quicksort(arr, i + 1, hi);
return arr;
}How the snippet works
Quicksort With Median Of Three Pivot (JavaScript) is built around the functions mid and quicksort.
Repetition is confined to for (let j = lo; j < hi; j++) — the rest of the file is straight-line.
What to watch for
- The guard
lo >= hishort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The primary signature is const mid = (lo + hi)
Statements that matter
if (arr[mid] < arr[lo]) [arr[lo], arr[mid]] = [arr[mid], arr[lo]];
if (arr[mid] < arr[hi]) [arr[hi], arr[mid]] = [arr[mid], arr[hi]];
if (arr[j] < pivot) { [arr[i], arr[j]] = [arr[j], arr[i]]; i++; }
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `mid`, `quicksort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.