Definition of Inversion: Let (A[0], A[1] ... A[n], n <= 50) be a sequence of n numbers. If i < j and A[i] > A[j], then the pair (i, j) is called inversion of A.
Example:Count(Inversion({3, 1, 2})) = Count({3, 1}, {3, 2}) = 2
思路,如果用brute force,则O(n^2),借用合并排序里面的合并步骤里的思路
import java.util.Arrays;
public class MergeSort {
static int InversionCount = 0;
public static void main(String[] args) {
int[] array = {3,1,2,5,4,7,6};
MergeSort(array, 0, array.length-1);
System.out.println(InversionCount);
System.out.println(Arrays.toString(array));
}
public static void MergeSort(int[] array, int lhs, int rhs) {
if (lhs < rhs) {
int mid = lhs + ((rhs - lhs)>>1);
MergeSort(array, lhs, mid);
MergeSort(array, mid+1, rhs);
Merge(array, lhs, mid, rhs);
}
}
public static void Merge(int[] array, int lhs, int mid, int