题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007
public class test {
public static void main(String[] args) {
int[] array = {1,2,3,4,5,6,7,0};
test test = new test();
int i = test.InversePairs(array);
for(int a:array){
System.out.println(a);
}
System.out.println(i);
}
public static int count = 0;//设置全局变量来记录逆序个数
public int InversePairs(int [] array) {
if(array.length == 0){
return 0;
}
int [] temp = new int[array.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
return Sort(array,0,array.length-1,temp)%1000000007;
}
private int Sort(int [] arry,int start, int end,int [] temp){
if(start >= end)
return 0;
int mid = (start+end)/2;
Sort(arry,start,mid,temp);
Sort(arry,mid+1,end,temp);
return Merge(arry,start,mid,end,temp);
}
private int Merge(int [] array, int left,int mid, int right, int[] temp){
int temp1 = left;
int temp2 = mid+1;
int temp3 = 0;
while (temp1 <= mid && temp2 <= right){
if(array[temp1] <= array[temp2]){
temp[temp3++] = array[temp1++];
}else {
temp[temp3++] = array[temp2++];
count += temp2-temp1-1;
}
}
while (temp1<=mid){
temp[temp3++] = array[temp1++];
}
while (temp2<=right){
temp[temp3++] = array[temp2++];
}
//将temp中的元素全部拷贝到原数组中(要注意使用的是left和t,不能搞混了t和left)
int i = 0;
while (left<=right){
array[left++] = temp[i++];
}
return count;
}
}