数组中的逆序对

#include <iostream>
//#include <string>
using namespace std;

//数组中的逆序对
//input: {7, 5, 6, 4}
//output: 5(分别是(7,5)、(7,6)、(7,4)、(5,4)、(6,4))

//时间复杂度为O(n2)
int InversePairs1(int* numbers, int length)
{
	int count = 0;
	for(int i=0; i<length-1; i++)
	{
		int j = i + 1;
		for(; j<length; j++)
		{
			if(numbers[i] > numbers[j])
				count++;
		}
	}
	return count;
}

/*********************************************************

先把数组分割成子数组,先统计出子数组内部的逆序对的数目,
然后再统计出两个相邻子数组之间的逆序对的数目。统计逆序对
过程中,还需要对数组进行排序,不难发现,这个排序过程实际上
就是归并排序。

**********************************************************/
//时间复杂度为O(nlogn),空间复杂度O(n),利用空间消耗换来了时间效率的提升
int InversePairsCore(int* numbers, int* copy, int start, int end);
int InversePairs2(int* numbers, int length)
{
	if(numbers == NULL || length < 0)
		return 0;
	int* copy = new int[length];
	for(int i=0; i<length; i++)
		copy[i] = numbers[i];

	int count = InversePairsCore(numbers, copy, 0, length-1);
	delete[] copy;

	return count;
}

int InversePairsCore(int* numbers, int* copy, int start, int end)
{
	if(start == end)
	{
		copy[start] = numbers[start];
		return 0;
	}

	int length = (end - start)/2;
	int left = InversePairsCore(numbers, copy, start, start + length);
	int right = InversePairsCore(numbers, copy, start + length +1, end);

	int i = start + length;
	int j = end;
	int indexCopy = end;
	int count = 0;
	while(i>=start && j>=start+length+1)
	{
		if(numbers[i] > numbers[j])
		{
			copy[indexCopy--] = numbers[i--];
			count += j - start - length;
		}
		else
		{
			copy[indexCopy--] = numbers[j--];
		}
	}

		for(; i>=start; --i)
			copy[indexCopy--] = numbers[i];

		for(; j>=start+length+1; --j)
			copy[indexCopy--] = numbers[j];

		return left + right + count;
}

int main()
{
	int numbers[] = {7, 5, 6, 4};
	int length = sizeof(numbers)/sizeof(int);
	cout<<"InversePairs1:"<<InversePairs1(numbers, length)<<endl;
	cout<<"InversePairs2:"<<InversePairs1(numbers, length)<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值