C++版本代码如下
#include <iostream>
#include <math.h>
#include <cstring>
using namespace std;
#define MAXSIZE 256
int num = 0; // 全局变量或者成员变量
void merge(int a[], int low, int middle, int high) {
int i = low, j = middle + 1, k = 0;
int tmp[high - low + 1];
while (i<=middle && j<=high) {
if (a[i] <= a[j])
tmp[k++] = a[i++];
else{
// 统计i与middle之间,比a[j]大的元素个数
num += (middle - i + 1);
tmp[k++] = a[j++];
}
}
// 处理剩下的
while (i <= middle)
tmp[k++] = a[i++];
while (j <= high)
tmp[k++] = a[j++];
// 从tmp拷贝回a
for (i = 0; i < high - low + 1; ++i) {
a[low + i] = tmp[i];
}
}
void mergeSortCounting(int a[], int low, int high) {
if (low >= high) return;
int middle = low + ((high - low)>>1);
mergeSortCounting(a, low, middle);
mergeSortCounting(a, middle+1, high);
merge(a, low, middle, high);
}
int main(int argc, char* argv[]){
int arr[6] = {1,5,6,2,3,4};
mergeSortCounting(arr, 0, 5);
for(int i = 0; i < 6; i++){
cout<<arr[i]<<" ";
}
cout<<endl<<num;
return 0;
}