# Inverse Pairs in Sword Finger offer (33) Array

## Title Description

In an array, if the first number is larger than the last number, the two numbers form an inverse pair. Input an array to find the total number of inverse pairs in the array P. And the output of P to 1000000007 is given. That is to say, output P%1000000007

Merge sorting is just that after each sorting, each module is put into a new lisy to achieve the purpose of reordering.

Since each small module is sorted, the comparison between them is before sorting, so that the sorting will not affect the results.

The results were obtained by comparing each group with the other.

```public class Solution {
public int InversePairs(int [] arr) {
if(arr == null || arr.length == 0)
return 0;
int[] copy = new int[arr.length];
int count = help(arr, copy, 0, arr.length - 1);
return count;

}
private int help(int[] arr, int[] copy, int low, int high){
if(low == high)
return 0;
int mid = (low + high) / 2;
int leftCount = help(arr, copy, low, mid) % 1000000007;
int rightCount = help(arr, copy, mid+1, high) % 1000000007;

int count = 0;
int i = mid;
int j = high;
int copyIndex = high;

while(i >= low && j > mid){
if(arr[i] > arr[j]){
count = count + j - mid;
copy[copyIndex--] = arr[i--];
if(count >= 1000000007){
count = count % 1000000007;
}
}else
copy[copyIndex--] = arr[j--];
}
for(; i >= low; i--){
copy[copyIndex--] = arr[i];
}
for(; j >mid; j--){
copy[copyIndex--] = arr[j];
}
for(int s=low;s <= high;s++){
arr[s] = copy[s];
}
return (leftCount + rightCount + count) % 1000000007;
}

}```

Posted by forums on Wed, 09 Oct 2019 19:44:46 -0700