If the target were to find the number of pairs i < j
such that arr[i] > arr[j]
, it would be the inversion count, that can be determined by merge-sorting the array and counting how many values each item is moved past.
Here, we can do the same, if we sort in descending order.
int pairs_count(int[] arr, int lo, int hi) {
if (hi <= lo) return 0;
int mid = (lo+hi)/2;
int count = pairs_count(arr, lo, mid);
count += pairs_count(arr, mid+1,hi);
count += merge(arr, lo, mid, hi);
return count;
}
int merge(int[] arr, int lo, int mid, int hi) {
int[] scratch = new int[hi-lo+1];
int l = lo, r = mid+1, k = 0, count = 0;
while(l <= mid && r <= hi) {
if (arr[r] > arr[l]) {
scratch[k++] = arr[r++];
count += mid-l+1;
} else {
scratch[k++] = arr[l++];
}
}
while(l <= mid) {
scratch[k++] = arr[l++];
}
while(r <= hi) {
scratch[k++] = arr[r++];
}
for(k = 0; k < scratch.length; ++k) {
arr[lo+k] = scratch[k];
}
retrun count;
}
call it with pairs_count(arr, 0, arr.length - 1);
.