#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;
}
12-11