Mergesort Inversion Count (Rust)
Count inversions in a Rust slice using a modified mergesort that counts crossings during the merge step.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.