题目:在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
代码如下:
package demo;
/**
* 数组中的逆序对
*
* @author xiangdonglee
*
*/
public class Test36 {
public static int inversePairs(int[] data) {
if (data == null || data.length < 1) {
throw new IllegalArgumentException("arg should not be null or empty!");
}
int[] copy = new int[data.length];
System.arraycopy(data, 0, copy, 0, data.length);
return inversePairsCore(data, copy, 0, data.length - 1);
}
private static int inversePairsCore(int[] data, int[] copy, int start, int end) {
if (start == end) {
copy[start] = data[start];
return 0;
}
int length = (end - start) / 2;
int left = inversePairsCore(copy, data, start, start + length);
int right = inversePairsCore(copy, data, start + length + 1, end);
// 前半段的最后一个数字的下标
int i = start + length;
// 后半段的最后一个数字的下标
int j = end;
// 开始拷贝的位置
int indexCopy = end;
// 逆序数
int count = 0;
while (i >= start && j >= start + length + 1) {
if (data[i] > data[j]) {
copy[indexCopy] = data[i];
indexCopy--;
i--;
count += j - (start + length);
} else {
copy[indexCopy] = data[j];
indexCopy--;
j--;
}
}
for (; i >= start; i--) {
copy[indexCopy] = data[i];
indexCopy--;
j--;
}
return count + left + right;
}
public static void main(String[] args) {
int[] data1 = { 1, 2, 3, 4, 7, 6, 5 };
System.out.println("1,2,3,4,7,6,5的逆序对个数:" + inversePairs(data1));
int[] data2 = { 6, 5, 4, 3, 2, 1 };
System.out.println("6,5,4,3,2,1的逆序对个数:" + inversePairs(data2));
int[] data3 = { 1, 2, 3, 4, 5, 6 };
System.out.println("1,2,3,4,5,6的逆序对个数:" + inversePairs(data3));
int[] data4 = { 1 };
System.out.println("1的逆序对个数:" + inversePairs(data4));
int[] data5 = { 1, 2 };
System.out.println("1,2的逆序对个数:" + inversePairs(data5));
int[] data6 = { 2, 1 };
System.out.println("2,1的逆序对个数:" + inversePairs(data6));
int[] data7 = { 1, 2, 1, 2, 1 };
System.out.println("1,2,1,2,1的逆序对个数:" + inversePairs(data7));
}
}