逆序数

逆序数

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。
如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。

Input
第1行:N,N为序列的长度(n <= 50000)
第2 - N + 1行:序列中的元素(0 <= A[i] <= 10^9)

Output
输出逆序数

Input示例

4
2
4
3
1

Output示例

4

一、冒泡排序做法(超时)

import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] arrs = new int[n];
		int k = 0;
		int count = 0;
		int temp = n;
		while(temp--!=0){
			arrs[k++] = scan.nextInt();
		}
		for(int i=0;i<n-1;i++){
			for(int j=i+1;j<n;j++){
				if(arrs[i]>arrs[j])
					count++;
			}
		}
		System.out.println(count);
	}
}

二、归并排序做法(推荐)

import java.util.Scanner;
public class Main{
	public static int count = 0;
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] arrs = new int[n];
		int k = 0;
		int temp = n;
		while(temp--!=0){
			arrs[k++] = scan.nextInt();
		}
		sort(arrs,0,arrs.length-1);
		System.out.println(count);
	}
	public static void mergeSort(int[] a,int low,int mid,int high){
		int i = low;		// 左指针
		int j = mid + 1;	//右指针
		int k = 0;
		int[] nums = new int[high-low+1];  //临时数组
		// 把较小的数先移到新数组中
		while(i<=mid&&j<=high){
			if(a[i]<a[j]){
				nums[k++] = a[i++];
			}else{
				nums[k++] = a[j++];
				count+=mid - i +1; //关键代码
			}
		}
		 // 把左边剩余的数移入数组
		while(i<=mid){
			nums[k++] = a[i++];
		}
		// 把右边边剩余的数移入数组
		while(j<=high){
			nums[k++]  = a[j++];
		}
		 // 把新数组中的数覆盖nums数组
		for(int m =0;m<nums.length;m++){
			a[m+low] = nums[m];
		}
	}
	public static void sort(int[] a,int low,int high){
		int mid = (low+high)/2;
		if(low<high){
			sort(a,low,mid);	//左边有序
			sort(a,mid+1,high); //右边有序
			mergeSort(a,low,mid,high); //左右归并
		}
	}
}
原文地址:https://www.cnblogs.com/hgnulb/p/10041567.html