</pre><pre name="code" class="cpp"><pre name="code" class="cpp">#include<array>
#include<vector>
#include<assert.h>
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
#define ARRAY_SIZE 5
/************************************************************************/
/* all inversions are calculated in the merge process */
/************************************************************************/
int mergeAndCount(vector<int> &Array,int l,int m,int r )
{
assert(m>=l && m<=r);
vector<int> L(Array.begin()+l,Array.begin()+m+1);
vector<int>R(Array.begin()+m+1,Array.begin()+r+1);
int p =0,q= 0,pa=l;
int inversionCount = 0;
while (p!=L.size() &&q!=R.size())
{
if (L[p]<=R[q])
{
Array[pa++] =L[p++];
}
else
{
Array[pa++] = R[q++];
inversionCount += L.size()-p;
}
}
while (p!=L.size() )
{
Array[pa++] = L[p++];
}
while (q!=R.size())
{
Array[pa++] = R[q++];
}
assert(pa==r+1);
return inversionCount;
}
/************************************************************************/
/* divide the array and and count each part's inversion-number,then sum them up */
/************************************************************************/
long long sortAndCount(vector<int> &Array,int l,int r)
{
if (l>=r)
return 0;
else
{
int m = (l+r)/2;
long long LV =sortAndCount(Array,l,m);
long long RV = sortAndCount(Array,m+1,r);
long long RC = mergeAndCount(Array,l,m,r);
return (LV+RV+RC);
}
}
/************************************************************************/
/* read numbers in the file */
/************************************************************************/
vector<int> readNumbers(string File)
{
ifstream file(File);
vector<int> result;
if (file.fail())
{
cout<<"ERROR: fail to read file!"<<endl;
return result;
}
string row_num;
while (getline(file,row_num))
{
//convert string to int
int temp;
stringstream stringBuffer;
stringBuffer<<row_num;
stringBuffer>>temp;
result.push_back(temp);
}
file.close();
return result;
}
int main()
{
vector<int>numbers = readNumbers(string("E:\\Q5.txt"));
cout<<"inversion numbers:"<<sortAndCount(numbers,0,numbers.size()-1)<<endl;
system("pause");
}