Let { A1,A2,…,An } be a permutation of the set{ 1,2,…, n}. If i < j and Ai > Aj then the pair (Ai,Aj) is called an “inversion” of the permutation. For example, the permutation {3, 1, 4, 2} has three inversions: (3,1), (3,2) and (4,2). The inversion table B1,B2,…,Bn of the permutation { A1,A2,…,An } is obtained by letting Bj be the number of elements to the left of j that are greater than j. (In other words, Bj is the number of inversions whose second component is j.) For example, the permutation:
- { 5,9,1,8,2,6,4,7,3 }
- has the inversion table
- 2 3 6 4 0 2 2 1 0.
- since there are 2 numbers, 5 and 9, to the left of 1; 3 numbers, 5, 9 and 8, to the left of 2; etc. your task is to convert a permutation to its inversion table, or vise versa, to convert from an inversion table to the corresponding permutation. (Use divide and conquer method)
- (4) Implement MergeSort algorithm using any programming language.
思路
从左到右依次扫描,比较两个各取一个数的大小,如果左边第一个数比右边第一个数大,那么左边排列的其他数字也可以和右边第一个数构成逆序数,以此类推。
代码实现
public static int[] getInversion (int []nums){
int []res = new int[nums.length];
cut(nums,res);
return res;
}
public static int[] cut(int []nums,int [] res){
if(nums.length<=1){
return nums;
}
int half = nums.length>>1;
int[] left = Arrays.copyOfRange(nums, 0, half);
int[] right = Arrays.copyOfRange(nums, half, nums.length);
return merge(cut(left,res),cut(right,res),res);
}
public static int[] merge(int []left,int[]right,int [] res){
int [] temp = new int[left.length+right.length];
int l = 0;
int r = 0;
int rLen = right.length-1;
int lLen = left.length-1;
for (int j = 0; j < temp.length; j++) {
if (l > lLen){
temp[j] = right[r++];
}else if( r > rLen){
temp[j] = left[l++];
}else if(left[l] <= right[r]){
temp[j] = left[l++];
}else{
res[right[r]-1] += lLen-l+1;
temp[j] = right[r++];
}
}
return temp;
}
测试
public static void main(String[] args) {
int []num = {5,9,1,8,2,6,4,7,3};
int[] cut = getInversion (num);
for (int i = 0; i < cut.length; i++) {
System.out.print(i+" ");
}
}