Problem Statement
I am attempting to solve this problem.
Short summary of the problem: Given an unsorted array, find the total number of inversion pairs. Definition of inversion: index i and j forms a valid inversion pair if i < j && arr[i] > arr[j]
My approach:
- I attempted to solve this with Divide and Conque. I divided the array into two parts and recursively solve each of them.
- After the recursive call is completed, each half should be sorted and should return the number of the inversion count.
The answer for the current array will be the sum of answers from both halves + the number of inversion pairs between both halves.
See this figure for a better understanding of this step:
Photo Credit: geeks for geeks
- To find the number of crossing inversions, I looped over the first array and for each element, I did a binary search in the second half to get the location of the exact element or the location of the first bigger element(more about this here).
While this approach seems correct to me and passes few test cases, it gives a wrong answer to some hidden test cases.
I need help understanding if there is any flaw in my algorithm or implementation.
My implementation:
static long inversionCount(long arr[], long N){
return solve(0, (int)N-1, arr);
}
static long solve(int l, int r, long[] arr){
if(l >= r) return 0;
int mid = l+(r-l)/2;
long countL = solve(l, mid, arr); //solve left half
long countR = solve(mid+1, r, arr); //solve right half
long countM = 0;
//count crossing inversions
for(int idx = l; idx <= mid; idx++){
int position = Arrays.binarySearch(arr, mid+1, r+1, arr[idx]);
if(position<0) position = -(position+1);
countM += position-mid-1;
}
Arrays.sort(arr, l, r);
return countM+countL+countR;
}