#include <iostream>
#include <algorithm>
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
long long numberOfInvertion; // the number of invertions.
long long SortAndCount(vector <int> &v, int low, int high);
long long MergeAndCount (vector <int> &v, vector <int> &vTemp, int low, int mid, int high);
void CopyToOriginalVector(vector <int> &vTemp, vector <int> &v, int low, int high);
int main () {
char fileName[] = "Q5.txt";
vector <int> v;
FILE *rp;
rp = fopen(fileName,"r");
// get the number from input file.
if (rp == NULL) {
cout << fileName << "open failed!"<<endl;
exit(0);
}
int temp;
while (!feof(rp)) {
fscanf(rp, "%d", &temp);
v.push_back(temp);
}
fclose(rp);
numberOfInvertion = SortAndCount(v, 0, v.size());
cout << "There are " << numberOfInvertion << " in Q5.txt !"<<endl;
system("pause");
return 0;
}
long long SortAndCount(vector <int> &v, int low, int high) {
long long leftInvertion = 0, rightInvertion = 0;
long long crossInvertion = 0;
if (low < high) {
int mid = low + (high - low) / 2;
leftInvertion = SortAndCount(v, low, mid);
rightInvertion = SortAndCount(v, mid + 1, high);
vector <int> vTemp;
crossInvertion = MergeAndCount(v, vTemp, low, mid, high);
CopyToOriginalVector(vTemp, v, low, high);
}
return (leftInvertion + rightInvertion + crossInvertion);
}
long long MergeAndCount (vector <int> &v, vector <int> &vTemp, int low, int mid, int high) {
vTemp.clear();
long long sumInvertion = 0;
int i = low;
int j = mid + 1;
while ((i < mid ) && (j < high)) {
if (v[i] > v[j]) {
vTemp.push_back(v[j++]);
sumInvertion += (mid - i);
}
else {
vTemp.push_back(v[i++]);
}
}
while (i < mid) {
vTemp.push_back(v[i++]);
}
while (j < high) {
vTemp.push_back(v[j++]);
}
return sumInvertion;
}
void CopyToOriginalVector(vector <int> &vTemp, vector <int> &v, int low, int high) {
v.clear();
for (int i = low; i < high; i++) {
v.push_back(vTemp[i]);
}
}
归并排序求逆序数
最新推荐文章于 2021-08-12 10:59:14 发布