Created
July 13, 2013 15:22
-
-
Save sunloverz/5991073 to your computer and use it in GitHub Desktop.
Countring the number of inversions in an array using divide and conguer algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <sstream> | |
#include <queue> | |
#include <stdio.h> | |
#include <fstream> | |
using namespace std; | |
#define INF 19999999 | |
long long int glob; | |
long long int merge( int *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(); | |
} | |
} | |
while( !left.empty() ) { arr[index++]=left.front();left.pop(); } | |
while( !right.empty() ) { arr[index++]=right.front();right.pop(); } | |
return ret; | |
} | |
void mergesortInvCount(int *arr, int beg, int end ) { | |
if( beg < end ) { | |
int mid = (int)((beg+end)/2); | |
mergesortInvCount( arr, beg, mid ); | |
mergesortInvCount( arr, mid+1, end ); | |
glob += merge(arr, beg, mid, end ); | |
} | |
} | |
int main() { | |
int arr[] = {2, 4, 1, 3, 5};//{1, 20, 6, 4, 5}; | |
mergesortInvCount(arr,0,4); | |
printf(" Number of inversions are %d \n",glob); | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment