Skip to content

Instantly share code, notes, and snippets.

@sunloverz
Created July 14, 2013 15:01
Show Gist options
  • Save sunloverz/5994548 to your computer and use it in GitHub Desktop.
Save sunloverz/5994548 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
#include <sstream>
#include <queue>
#include <stdio.h>
#include <fstream>
using namespace std;
ifstream infile("IntegerArray.txt");
unsigned long long glob=0;
long long int merge( long *arr, int beg, int mid, int end ) {
queue<int> left;
queue<int> right;
for( int i=beg; i<=mid; ++i ) {
left.push(arr[i]);
}
for( int i=mid+1; i<=end; ++i ) {
right.push(arr[i]);
}
int index=beg;
int ret=0;
while( !left.empty() && !right.empty() ) {
if( left.front() <= right.front() ) {
arr[index++] = left.front();
left.pop();
} else {
arr[index++] = right.front();
right.pop();
ret+=left.size();
if(left.size()<0){
cout<<left.size()<<endl;
}
}
}
while( !left.empty() ) { arr[index++]=left.front();left.pop(); }
while( !right.empty() ) { arr[index++]=right.front();right.pop(); }
return ret;
}
void mergesortInvCount(long *arr, int beg, int end ) {
if( beg < end ) {
int mid = (int)((beg+end)/2);
cout<<"Before the 1st Call"<<endl;
mergesortInvCount( arr, beg, mid );
cout<<"After the 1st Call"<<endl;
mergesortInvCount( arr, mid+1, end );
cout<<"After the 2nd Call"<<endl;
glob += merge(arr, beg, mid, end );
cout<<"After the merge"<<endl;
}
}
int main() {
long arr[] = {2,4,1,3,5};
mergesortInvCount(arr,0,4);//99999
cout<<glob<<endl;
system("pause");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment