Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- void print_array(int a[],int n)
- {
- for ( int i = 0; i < n; i++ )
- printf( "%d ",a[i]);
- printf( "\n");
- }
- int MergeandCountSplitInv(int a[], int l, int m, int r)
- {
- int i,j,k;
- int *b, *c;
- b = (int*)malloc(100);
- c = (int*)malloc(100);
- int t1 = 0;
- for(i = l; i <= m; i++)
- *(b+(t1++)) = a[i];
- int t2 = 0;
- for(j = m+1; j <= r; j++)
- *(c+(t2++)) = a[j];
- i=l;
- j=m+1;
- k = l;
- int i1,j1;
- i1=0;
- j1=0;
- int inversion = 0;
- int remain_elem = 0;
- while(i1<t1&&j1<t2) {
- if(b[i1]<c[j1])
- a[k++] = b[i1++];
- else
- {
- // count remain elements of array b
- remain_elem = t1 - i1;
- inversion += remain_elem;
- a[k++] = c[j1++];
- }
- }
- while(i1<t1)
- a[k++] = b[i1++];
- while(j1<t2)
- a[k++] = c[j1++];
- free(b);
- free(c);
- print_array(a,7);
- return inversion;
- }
- int SortandCount(int a[], int l, int r)
- {
- int m;
- int x,y,z;
- if(l>=r)
- return 0;
- else {
- m = (int)((l+r)/2);
- x = SortandCount(a,l,m);
- y = SortandCount(a,m+1,r);
- z = MergeandCountSplitInv(a,l,m,r);
- }
- return x+y+z;
- }
- int main(int argc, char* argv)
- {
- int a[] = { 2,7,6,3,4,5,1};
- int n = sizeof(a)/sizeof(int);
- printf("%d\n",SortandCount(a,0,n-1));
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment