首页 > 其他 > 详细

计算逆序对

时间:2020-03-10 23:17:49      阅读:79      评论:0      收藏:0      [点我收藏+]

归并排序(计算逆序对)

import java.io.BufferedInputStream;
import java.util.Scanner;

public class test06 {
    static int count = 0;

    public static void main(String[] args) {
        Scanner scan = new Scanner(new BufferedInputStream(System.in));
        int n = scan.nextInt();
        scan.nextLine();
        String[] str = scan.nextLine().split(" ");
        int[] num = new int[str.length];
        for (int i = 0; i < num.length; i++) {
            num[i] = Integer.parseInt(str[i]);
        }
        sort(num, 0, num.length);//归并排序
        System.out.println(count);
    }

    static void sort(int[] num, int begin, int end) {
        int temp = (end - begin) / 2;
        if (temp > 0) {
            sort(num, begin, end - temp);
            sort(num, end - temp, end);
        }
        megre(num, begin, end - temp, end - temp, end);
    }

    static void megre(int[] num, int b1, int e1, int b2, int e2) {
        int[] temp = new int[e2 - b1];
        int i = 0, m = b1, n = b2;
        for (; m < e1 && n < e2; i++) {
            if (num[m] < num[n]) {
                temp[i] = num[m];
                m++;
            } else {
                count = count + e1 - m;//根据题意计算的逆序对
                temp[i] = num[n];
                n++;
            }
        }
        for (int j = i; j < temp.length; j++) {
            if (m < e1) {
                temp[j] = num[m];
                m++;
            }
            if (n < e2) {
                temp[j] = num[n];
                n++;
            }
        }
        for (int j = 0; j < temp.length; j++) {
            num[j + b1] = temp[j];
        }

    }
}

计算逆序对

原文:https://www.cnblogs.com/continued258/p/12459331.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!