编程练习-求出数组逆序对

编程练习-求出数组逆序对

思路:
刚开始使用一个个遍历所有数对然后比较算出,时间复杂度为O(n^2);后来思考后发现可以基于归并排序来实现优化,归并排序可以在选出较大数字的过程,记录后半部分中小于前半部分某个数字的个数…
代码如下:

public class Main {
    private static int res = 0;//逆序对个数
    public static void main(String[] args) {
        //归并排序
        int[] array = {364,637,341,406,747,995,234,971,571,219,993,407,416,366,315,301,601,650,418,355,460,505,360,965,516,648,727,667,465,849,455,181,486,149,588,233,144,174,557,67,746,550,474,162,268,142,463,221,882,576,604,739,288,569,256,936,275,401,497,82,935,983,583,523,697,478,147,795,380,973,958,115,773,870,259,655,446,863,735,784,3,671,433,630,425,930,64,266,235,187,284,665,874,80,45,848,38,811,267,575};
        int[] temp = new int[array.length];
        for(int i=0;i<array.length;++i){
            temp[i] = array[i];
        }
        mergeSort(array,temp,0,array.length-1);

        for(int n:array) {
            System.out.print(n+" ");
        }
        System.out.println(res);
    }

    private static void mergeSort(int[] array, int[] temp, int s, int e) {
        if(s>=e) {
            temp[s] = array[s];
            return;
        }
        int m = (s+e)/2;
        mergeSort(array,temp,s,m);
        mergeSort(array,temp,m+1,e);
        int c = e;
        int i = m;
        int j = e;
        while(i>=s&&j>=m+1){
            if(temp[i]>temp[j]){
                array[c] = temp[i];
                i--;
                res += j-m;
            }else{
                array[c] = temp[j];
                j--;
            }
            c--;
        }
        while(i>=s){
            array[c] = temp[i];
            i--;
            c--;
        }
        while(j>=m+1){
            array[c] = temp[j];
            j--;
            c--;
        }

        for(int z=s;z<=e;z++){
            temp[z] = array[z];
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值