Quicksort With Median Of Three Pivot (Rust)
Sort a Rust slice in place using quicksort with median-of-three pivot selection to avoid worst-case behavior.
Code
fn quicksort(arr: &mut [i32]) {
if arr.len() < 2 { return; }
let pivot_idx = partition(arr);
quicksort(&mut arr[..pivot_idx]);
quicksort(&mut arr[pivot_idx + 1..]);
}
fn partition(arr: &mut [i32]) -> usize {
let n = arr.len();
let mid = n / 2;
if arr[mid] < arr[0] { arr.swap(0, mid); }
if arr[n - 1] < arr[0] { arr.swap(0, n - 1); }
if arr[mid] < arr[n - 1] { arr.swap(n - 1, mid); }
let pivot = arr[n - 1];
let mut i = 0;
for j in 0..n - 1 { if arr[j] < pivot { arr.swap(i, j); i += 1; } }
arr.swap(i, n - 1);
i
}Inside the snippet
The working surface is the functions quicksort and partition — everything else is wiring.
Repetition is confined to for j in 0..n - 1 { if arr[j] < pivot { arr.swap(i, j); i += 1; } } — the rest of the file is straight-line.
Putting it to use
Entry signature: fn quicksort(arr: &mut [i32])
The surface worth importing is quicksort; the helpers around it are private to the snippet.
Core lines
for j in 0..n - 1 { if arr[j] < pivot { arr.swap(i, j); i += 1; } }
fn quicksort(arr: &mut [i32]) {
if arr.len() < 2 { return; }
let pivot_idx = partition(arr);
quicksort(&mut arr[..pivot_idx]);
quicksort(&mut arr[pivot_idx + 1..]);
}
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
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `quicksort`, `partition` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.