在数组中的两个数字如果前面一个大于后面的数字,则这两个数字组成一个逆序对,输入一个数组,求出这个数组的逆序对的总数。
思路:利用变形的归并排序
#include <iostream> using namespace std; int inversePairs(int *data, int *buf, int l, int r){ if (l >= r) return 0; //初始化需要的变量,p1指向左子数组的最右,p2指向右子数组的最右 int count = 0; int mid = (l + r) / 2; int p1 = mid; int p2 = r; int lPairs = inversePairs(data, buf, l, mid); int rPairs = inversePairs(data, buf, mid + 1, r); int length = r - l + 1; //数据复制到辅助数组 for (int curr = l; curr <= r; curr ++){ buf[curr] = data[curr]; } //归并并且排序,注意讨论分支出现的顺序,避免数组操作出界 for (int curr = r; curr >= l; curr--){ if (p1<l){ data[curr] = buf[p2--]; }else{ if (p2 < mid + 1){ data[curr] = buf[p1--]; }else{ if (buf[p1] > buf[p2]){ data[curr] = buf[p1--]; count += (p2 - mid); }else{ data[curr] = buf[p2--]; } } } } return (lPairs + rPairs + count); } int main(){ #if 0 int data[4] = {7,5,6,4}; int temp[4] = { 0 }; int myCount = inversePairs(data, temp, 0, 3); for (int i = 0; i < 4; i++) cout << data[i]<<' '; cout << endl; cout << myCount; #endif const int num = 6; int data[num] = { 6, 2, 3, 6, 5, 0 }; int temp[num] = { 0 }; int myCount = inversePairs(data, temp, 0, 5); for (int i = 0; i < num; i++) cout << data[i] << ' '; cout << endl; cout << myCount; system("pause"); }