I\'m designing an algorithm to do the following: Given array A[1... n]
, for every i < j
, find all inversion pairs such that A[i] > A[j]
One possible solution in C++ satisfying the O(N*log(N)) time complexity requirement would be as follows.
#include
vector merge(vectorleft, vectorright, int &counter)
{
vector result;
vector::iterator it_l=left.begin();
vector::iterator it_r=right.begin();
int index_left=0;
while(it_l!=left.end() || it_r!=right.end())
{
// the following is true if we are finished with the left vector
// OR if the value in the right vector is the smaller one.
if(it_l==left.end() || (it_r!=right.end() && *it_r<*it_l) )
{
result.push_back(*it_r);
it_r++;
// increase inversion counter
counter+=left.size()-index_left;
}
else
{
result.push_back(*it_l);
it_l++;
index_left++;
}
}
return result;
}
vector merge_sort_and_count(vector A, int &counter)
{
int N=A.size();
if(N==1)return A;
vector left(A.begin(),A.begin()+N/2);
vector right(A.begin()+N/2,A.end());
left=merge_sort_and_count(left,counter);
right=merge_sort_and_count(right,counter);
return merge(left, right, counter);
}
It differs from a regular merge sort only by the counter.