逆序对,就是诸如 i<j 且 a[i]>a[j] 这样的数对 (i,j)
#include <iostream> using namespace std; const int size = 1000; int invers=0;//求逆序数 int tmpArr[size];//额外空间,用来暂存 void Copy(int a[], int b[], int low, int high) { for (int i = low; i <= high; ++i) a[i] = b[i]; } void Merge(int a[], int b[], int low, int high) { int mid = (low + high)/2; int i, j, k;//i指向[low,mid],j指向[mid+1,high]中的元素 for (i = low, j = mid+1, k = low; i <= mid && j <= high; k++) { if (a[i] < a[j]) b[k] = a[i++];//[low,mid]段中的第i个元素a[i]小于 [mid+1,high]段中的a[j],他应该放在前面,所以放入b[]中 else { //前面的数大于后面的数,有逆序数 //invers += ?? if (a[i] > a[j]) invers += mid-i+1; //a[i] > a[j], 则a中[i,mid]部分都会大于a[j] b[k] = a[j++];//只有放入了b[]后,i或j才++ } } while (i <= mid) b[k++] = a[i++]; while (j <= high) b[k++] = a[j++]; Copy(a, b, low, high);//将排好序的元素从b中复制给a } void MergeSort(int a[], int low, int high) { if (low >= high) return ;//递归出口,当区间左值大于等于右值,就不用排序了 int mid = (low + high)/2;//将区间[low,high]分成[low,mid],[mid+1, high]两段分别排序 MergeSort(a, low, mid); //或者分为[low,mid-1]和[mid,high],本程序采用前者 MergeSort(a, mid+1, high); Merge(a, tmpArr, low, high);//将排好序的 [low,mid],[mid+1, high]两段合并 // Copy(a, tmpArr, low, high);// } int main() { int arr[size], N, i; while (cin>>N) { invers = 0; for (i = 0; i < N; ++i) cin >> arr[i]; MergeSort(arr,0,N-1); for (i = 0; i < N-1; ++i) cout << arr[i] << " "; cout << arr[i] << endl; cout << "inverse number is " << invers << endl; } return 0; }