数组中的逆序对

题目描述: 有一组数,对于其中任意两个数组,若前面一个大于后面一个数字,则这两个数字组成一个逆序对,计算给定数组中的逆序对个数。
给定一个int数组A和它的大小n,请返回A中的逆序对个数。
测试样例:
[1,2,3,4,5,6,7,0],8
返回:7
解题思路:
**思路1:**顺序扫描整个数组,没扫描到一个数,就比较该数与后面数的大小,如果该数小于大于后面的数,就构成逆序对。若该数组中有n个数,则此算法的时间复杂度为O(n^2)。

public class Demo1 {
    public static int Count(int[] A,int n){
        int count = 0;
        for(int i = 0;i<A.length;i++){
            for(int j = i+1;j<A.length;j++){
                if (A[i] > A[j])
                 count++;
                }
            }
            return count;
        }

    public static void main(String[] args) {
        int[] A = new int[]{1,2,3,4,5,6,7,0};
        int c = Count(A,A.length);
        System.out.println(c);
    }
    }

思路2: 利用分治思想,采用归并排序来解决,归并排序的时间复杂度为O(n*log(n))。例如{6,5,4,7}这个数组,有4个数。
在这里插入图片描述
(1)先将数组分成一个一个的子数组,直到数组内只有一个数,即分成了{6}{5}{4}{7}四个数组。
(2)再将{6}{5}合并,一边排序一边统计逆序对。{4}{7}合并,一边排序一边统计逆序对。得到{5,6}{4,7}两个数组。
(3)再将{5,6}{4,7}两数组合并,一边排序一边统计逆序对,得到{4,5,6,7}结束。

public class  Main2{
    public static int count(int[] A,int n){
        if(A == null || n == 0){
            return 0;
        }
        return mergeSortRecursion(A,0,A.length);
    }
    public static int mergeSortRecursion(int[] array,int low,int high){
        //[low,high)
        if(high - 1 == low){
            return 0;
        }
        int mid = (high + low)/2;
        return mergeSortRecursion(array,low,mid)+ mergeSortRecursion(array,mid,high)+mergeCount(array,low,mid,high);
    }
    public static int mergeCount(int[] array,int low,int mid,int high){
        int i = low;
        int j = mid;
        int length = high - low;
        int[] newArray = new int[length];
        int k = 0;
        int sumReverse = 0;
        //选择小的放入到newArray中
        while(i<mid && j<high){
            if(array[i] <= array[j]){
                newArray[k++] = array[i++];
            }
            else{
                sumReverse += (mid - i);
                newArray[k++] = array[j++];
            }
        }
        while(i < mid){
            newArray[k++] = array[i++];
        }
        while(j < high){
            newArray[k++] = array[j++];
        }
        //从newArray搬回到array中
        for(int t = 0;t < length;t++){
            array[low + t] = newArray[t];
        }
        return sumReverse;
    }
    public static void main(String[] args) {
        int[] a = {1,6,7,8,2,5,3};
        int r = count(a,7);
        System.out.println(r);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值