I've been banging my head against this error for a couple of hours now and can't seem to find where the error is.
I'm trying to count the inversions in a given array and all my tests pass except when using this array as input [6, 1, 2, 5, 4, 3].
The logic is as follows; given array A[1... n], for every i < j, find all inversion pairs such that A[i] > A[j]
The number I receive for this array is 14 inversions and the correct answer is 8.
The code so far is this
function mergeCount(left: number[], right: number[]): number {
let count = 0;
let leftCounter = 0;
let rightCounter = 0;
while (leftCounter < left.length && rightCounter < right.length) {
if (left[leftCounter] < right[rightCounter]) {
leftCounter += 1;
} else {
count += left.length - leftCounter;
rightCounter += 1;
}
}
return count;
}
function countInversions(input: number[]): number {
if (input.length < 2) return 0;
const middle = Math.floor(input.length / 2);
const left = input.slice(0, middle);
const right = input.slice(middle);
return countInversions(left) + countInversions(right) + mergeCount(left, right);
}
Any idea what I'm missing or what's wrong with my code?
EDIT:
So the problem was that I wasn't sorting the arrays when splitting them up, I was just updating the counter. The working solution that I came up with is the following
function mergeCount(left: number[], right: number[]): { output: number[]; count: number } {
let count = 0;
let leftCounter = 0;
let rightCounter = 0;
const output: number[] = [];
while (leftCounter < left.length && rightCounter < right.length) {
if (left[leftCounter] < right[rightCounter]) {
output.push(left[leftCounter]);
leftCounter += 1;
} else {
output.push(right[rightCounter]);
count += left.length - leftCounter;
rightCounter += 1;
}
}
return {
output: output.concat(left.slice(leftCounter)).concat(right.slice(rightCounter)),
count,
};
}
function countInversions(input: number[]): { output: number[]; count: number } {
if (input.length < 2) return { output: input, count: 0 };
const middle = Math.floor(input.length / 2);
const { output: left, count: a } = countInversions(input.slice(0, middle));
const { output: right, count: b } = countInversions(input.slice(middle));
const { output, count: c } = mergeCount(left, right);
return { output, count: a + b + c };
}