在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
//第二种递归 给出停止条件,直到最底层才可以对递归结果依次进行处理
//第一种递归 同样给出停止条件,在再次调用递归前进行逻辑处理
//可以设置全局变量,每次都会更新全局变量
public class inversePairs {
public int InversePairs(int [] array) {
if(array==null || array.length<=0)
return 0;
int count = InversPairsCore(array,0,array.length-1);
return count;
}
private int InversPairsCore(int[] array, int start, int end) {
// TODO Auto-generated method stub
if(start == end)
return 0;
int mid = (start+end)/2;
//int count=0;
int left = InversPairsCore(array,start,mid);
int right = InversPairsCore(array,mid+1,end);
return (sort(array,start,mid,end)+left+right)%1000000007;
}
private int sort(int[] array, int start, int mid, int end) {
// TODO Auto-generated method stub
int i=mid,j=end,k=end-start+1;
int count=0;
int[] temp = new int[k];
int current = end-start;
while(i>=start && j>=mid+1) {
if(array[i]>array[j]) {
count=count+j-mid;
temp[current--] = array[i--];
if(count>1000000007)
count=count%1000000007;
}else {
temp[current--] = array[j--];
}
}
while(i>=start) {
temp[current--] = array[i--];
}
while(j>=mid+1) {
temp[current--] = array[j--];
}
for(int l=0;l<temp.length;l++)
array[start++]=temp[l];
return count;
}
}