Mergesort Inversion Count (Rust)

Count inversions in a Rust slice using a modified mergesort that counts crossings during the merge step.

RustData Integrity

Code

rustsnippet
19 lines
fn count_inversions(arr: &mut [i32]) -> i64 {
    let n = arr.len();
    if n < 2 { return 0; }
    let mut tmp = vec![0i32; n];
    fn merge(arr: &mut [i32], tmp: &mut [i32], lo: usize, mid: usize, hi: usize) -> i64 {
        let mut i = lo; let mut j = mid; let mut k = lo; let mut inv = 0i64;
        for x in lo..=hi { tmp[x] = arr[x]; }
        while i < mid && j <= hi { if tmp[i] <= tmp[j] { arr[k] = tmp[i]; i += 1; } else { arr[k] = tmp[j]; j += 1; inv += (mid - i) as i64; } k += 1; }
        while i < mid { arr[k] = tmp[i]; i += 1; k += 1; }
        while j <= hi { arr[k] = tmp[j]; j += 1; k += 1; }
        inv
    }
    fn sort(arr: &mut [i32], tmp: &mut [i32], lo: usize, hi: usize) -> i64 {
        if lo >= hi { return 0; }
        let mid = (lo + hi + 1) / 2;
        sort(arr, tmp, lo, mid - 1) + sort(arr, tmp, mid, hi) + merge(arr, tmp, lo, mid, hi)
    }
    sort(arr, &mut tmp, 0, n - 1)
}

What the code does

The working surface is the functions count_inversions, merge and sort — everything else is wiring.

Repetition is confined to for x in lo..=hi { tmp[x] = arr[x]; } — the rest of the file is straight-line.

Using it

The main signature reads fn count_inversions(arr: &mut [i32]) -> i64

count_inversions is what another module would consume; nothing else here is load-bearing for callers.

Key statements

fn sort(arr: &mut [i32], tmp: &mut [i32], lo: usize, hi: usize) -> i64 {
if lo >= hi { return 0; }
let mid = (lo + hi + 1) / 2;
sort(arr, tmp, lo, mid - 1) + sort(arr, tmp, mid, hi) + merge(arr, tmp, lo, mid, hi)
}
while i < mid { arr[k] = tmp[i]; i += 1; k += 1; }
while j <= hi { arr[k] = tmp[j]; j += 1; k += 1; }

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `count_inversions`, `merge`, `sort` at load time.