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.

RustData Integrity

Code

rustsnippet
19 lines
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

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.