【算法实验 Lab-report-unit-1-03】

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+" ");
        }
    }

在这里插入图片描述

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值