归并排序(计算逆序对)
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