思路:{7,5,6,4}={7,5},{7,4},{7,6},{5,4},{6,4}
暴力的话,时间复杂度为o(n^2)
这里可以使用归并的思想
class Offer36 {
static int count;
static void sort(int[] data, int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
sort(data, start, mid);
sort(data, mid + 1, end);
merge(data, start, mid, end);
}
}
static void merge(int[] data, int start, int mid, int end) {
int left = mid;
int right = end;
int[] temp = new int[end - start + 1];
int tempIndex = end - start;
while (left >= start && right > mid) {
if (data[left] > data[right]) {
count += (right - mid);
temp[tempIndex--] = data[left--];
} else {
temp[tempIndex--] = data[right--];
}
}
while (left >= start) {
temp[tempIndex--] = data[left--];
}
while (right > mid) {
temp[tempIndex--] = data[right--];
}
System.arraycopy(temp, 0, data, start, temp.length);
}
public static void main(String[] args) {
count = 0;
int[] test = {7, 5, 6, 4};
sort(test, 0, test.length - 1);
System.out.println(count);
}
}