Complete the code to initialize the inversion count variable.
let mut count = [1];We start counting inversions from zero because initially we have found none.
Complete the code to compare two elements for inversion.
if arr[i] [1] arr[j] { count += 1; }
An inversion is when a larger element appears before a smaller one, so we check if arr[i] > arr[j].
Fix the error in the loop to iterate over the array indices correctly.
for i in 0..[1] { for j in i+1..[2] { /* count inversions */ } }
We loop from 0 to arr.len() (exclusive) to cover all indices properly.
Fill both blanks to complete the merge step that counts split inversions.
while i < n1 && j < n2 { if left[i] [1] right[j] { arr[k] = left[i]; i += 1; } else { arr[k] = right[j]; count += (n1 - i) as i64; j += 1; } k += 1; }
We compare if left[i] < right[j] to merge sorted arrays and count inversions when left[i] > right[j].
Fill all three blanks to complete the recursive merge sort function that counts inversions.
fn merge_sort(arr: &mut [i32]) -> i64 {
let len = arr.len();
if len <= 1 {
return 0;
}
let mid = len [1] 2;
let mut count = 0;
count += merge_sort(&mut arr[0..[2]]);
count += merge_sort(&mut arr[[3]..len]);
count += merge(arr, mid);
count
}We divide the array by length/2, then recursively sort left (0..mid) and right (mid..len) parts.
