逆序对计数问题

#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
#include <Windows.h>
using namespace std;

int nums[] = { 13,8,10,6,15,18,};//12,20,9,14,17,19 

bool randNums(int n) {
	fstream ofs("data.txt", ios::out | ios::trunc);
	if (!ofs.is_open()) {
		cout << "文件打开失败!" << endl;
		return false;
	}
	ofs << n << ' ';
	int temp = 0;
	for (int i = 0; i < n; i++) {
		temp = rand() % 200;  //随机数在0到200
		ofs << temp << ' ';
	}
	return true;
}

//归并排序
int mergeCount(int nums[],int left,int mid,int right) 
{
	vector<int> nums_0;
	int k = 0, j = left, sum = 0;

	for(int i=mid;i<=right;i++)
	{
		while (nums[j] < nums[i] && j < mid)
		{
			nums_0.push_back(nums[j++]);
		}
		nums_0.push_back(nums[i]);
		sum += mid - j;
	}

	while (j < mid) 
	{
		nums_0.push_back(nums[j++]);
	}

	for (vector<int>::iterator it = nums_0.begin(); it != nums_0.end(); it++) {
		nums[left++] = *it;
	}

	return sum;
}

int countInver(int nums[],int left,int right)
{
	if (left >= right)
	{
		return 0;
	}
	int mid = floor((left + right) / 2);
	int S1 = countInver(nums, left, mid);
	int S2 = countInver(nums, mid + 1, right);
	int S3 = mergeCount(nums, left, mid + 1, right);
	return S1 + S2 + S3;
}

int* readNums() {
	fstream ifs("data.txt", ios::in);
	int n;
	ifs >> n;
	int i = 0;
	int* nums = new int[n];
	
	while (ifs >> n) {
		//cout << n << ' ';
		nums[i++] = n;
	}
	cout << endl;
	cout << endl;
	return nums;
}

int main() 
{
	int n = 10000;  //次数修改  次数太大 (int)sum溢出 
	srand((unsigned int)time(NULL));
	if (!randNums(n)) {
		return 0;
	}
	int* nums = readNums();

	cout << endl;
	clock_t sTime, eTime;
	sTime = clock();
	ULONGLONG startTime = GetTickCount64();

	cout << countInver(nums, 0, n-1) << endl;


	ULONGLONG endTime = GetTickCount64();
	eTime = clock();
	cout << "THe run time is:" << endTime - startTime << "ms" << endl;
	cout << "THe run time is:" << ((double)eTime - sTime) / CLOCKS_PER_SEC << "s" << endl;

	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值