package com.google.android;
public class InversePairs {
public static void main(String[] args) {
int[] data = { 7, 5, 6, 4 };
int count = inversePairs(data);
System.out.println(count);
}
private static int inversePairs(int[] data) {
if (data == null || data.length == 0) {
return 0;
}
int[] copy = new int[data.length];
System.arraycopy(data, 0, copy, 0, data.length);
int count = inversePairsCore(data, copy, 0, data.length - 1);
return count;
}
private static int inversePairsCore(int[] data, int[] copy, int start,
int end) {
// 递归结束条件
if (start == end) {
copy[start] = data[end];
return 0;
}
int length = (end-start) >> 1;
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--];
count += j - start - length;
} else {
copy[indexCopy--] = data[j--];
}
}
for (; i >= start; --i) {
copy[indexCopy--] = data[i];
}
for (; j >= start + length + 1; --j) {
copy[indexCopy--] = data[j];
}
return left + right + count;
}
}
数组中的逆序对
最新推荐文章于 2022-03-27 13:15:54 发布