Complete the code to initialize the inversion count variable.
let inversionCount = [1];We start counting inversions from zero because initially no pairs are counted.
Complete the code to compare two elements for inversion detection.
if (arr[i] [1] arr[j]) {
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 merge function to correctly count inversions.
while (i < left.length && j < right.length) { if (left[i] <= right[j]) { merged.push(left[i]); i++; } else { merged.push(right[j]); inversionCount += [1]; j++; } }
When an element from right is smaller, all remaining elements in left from index i form inversions.
Fill both blanks to complete the merge sort recursive calls.
const left = arr.slice(0, [1]); const right = arr.slice([2]);
We split the array into two halves: left from 0 to middle, right from middle to end.
Fill both blanks to complete the inversion count function using merge sort.
function countInversions(arr: number[]): number {
if (arr.length <= [1]) return 0;
const mid = Math.floor(arr.length / [2]);
const left = arr.slice(0, mid);
const right = arr.slice(mid);
let inversionCount = countInversions(left) + countInversions(right);
let i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
inversionCount += left.length - i;
}
}
while (i < left.length) arr[k++] = left[i++];
while (j < right.length) arr[k++] = right[j++];
return inversionCount;
}The base case is when array length is 1 or less, mid is found by dividing length by 2, and mid is used to slice the array.
