Count Reverse Pairs - C++

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值