I am getting a wrong answer from the following procedure in my attempt to count inversions from a very large dataset.
I have also tried a few of other codes that have been given/suggested on the related posts and did try a lot of manipulations in my code itself [to get answer right] but got rejected. Provided that I don't know the right answer, I can just only verify if I have one.
Also, In order to help myself more, I tried it with O(n^2)
way in order to get an answer right at least but the answer I got was rejected.
Code producing wrong output: -1887062008
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int mergeAndCount(vector<int> & arr, int first, int second, int last) {
vector<int> temp;
int i = first, j = second;
int invCount = 0;
while( i < second && j <= last ) {
if( arr[i] > arr[j] ) {
invCount += second - i;
temp.push_back( arr[j] );
j++;
}
else {
temp.push_back( arr[i] );
i++;
}
}
while( i < second ) {
temp.push_back( arr[i++] );
}
while ( j <= last ) {
temp.push_back( arr[j++] );
}
copy( temp.begin(), temp.end(), arr.begin()+first);
return invCount;
}
int sortAndCount( vector<int>& arr, int low, int high ) {
if( low >= high )
return 0;
int mid = low + (high-low)/2;
int lic = sortAndCount( arr, low, mid );
int ric = sortAndCount( arr, mid+1, high);
int ic = mergeAndCount( arr, low, mid+1, high);
return lic+ric+ic;
}
int getInversionCount(vector<int>& arr ) {
if( arr.size() > 0 )
return sortAndCount( arr, 0, arr.size()-1 );
return 0;
}
void Test1() {
vector<int> arr;
ifstream inFile;
inFile.open("w2.txt");
if (!inFile) {
cout << "Unable to open file datafile.txt";
}
int value;
while(inFile >> value) {
arr.push_back(value);
}
cout << getInversionCount( arr) << endl;
}
int main() {
Test1();
return 0;
}