#include <iostream>
#include <vector>
using namespace std;
int rev(int a[], const int low, const int high);
int reverse_helper(int a[], const int low, const int mid, const int high);
int main(){
int b[5] = {7, 3, 5, 2, 4};
int ans = rev(b, 0, 4);
cout<< ans <<endl;
cin.get();
return 0;
}
int reverse_helper(int a[], const int low, const int mid, const int high)
{
int * b = new int[high + 1 - low];
int h, j, k;
h = low;
j = mid + 1;
int i = 0;
int ret = 0;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
ret += mid - h + 1;
}
i++;
}
if(h > mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=0; k <= high - low; k++)
{
a[k + low] = b[k];
}
delete[] b;
return ret;
}
int rev(int a[], const int low, const int high) // Recursive sort ...
{
int mid;
if(low < high)
{
mid = (low + high)/2;
int a1 = rev(a, low, mid);
int a2 = rev(a, mid + 1, high);
int a3 = reverse_helper(a, low, mid, high);
return a1 + a2 + a3;
}
return 0;
}
Count Reverse Pair 是在 Merge Sort 的基础上修改一下,最后Merge step的时候数有多少Reverse Pairs