Advertisement
bkit4s0

[count inversion] bản hoàn chỉnh

Dec 19th, 2014
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.48 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. void print_array(int a[],int n)
  5. {
  6.        for ( int i = 0; i < n; i++ )
  7.                         printf( "%d ",a[i]);
  8.            printf( "\n");
  9. }
  10. int MergeandCountSplitInv(int a[], int l, int m, int r)
  11. {
  12.     int i,j,k;
  13.     int *b, *c;
  14.     b = (int*)malloc(100);
  15.     c = (int*)malloc(100);
  16.  
  17.     int t1 = 0;
  18.     for(i = l; i <= m; i++)
  19.         *(b+(t1++)) = a[i];
  20.     int t2 = 0;
  21.     for(j = m+1; j <= r; j++)
  22.         *(c+(t2++)) = a[j];
  23.  
  24.     i=l;
  25.     j=m+1;
  26.     k = l;
  27.         int i1,j1;
  28.         i1=0;
  29.         j1=0;
  30.     int inversion = 0;
  31.     int remain_elem = 0;
  32.     while(i1<t1&&j1<t2) {
  33.        if(b[i1]<c[j1])
  34.            a[k++] = b[i1++];
  35.        else
  36.        {
  37.            // count remain elements of array b
  38.            remain_elem = t1 - i1;
  39.            inversion += remain_elem;
  40.            a[k++] = c[j1++];
  41.        }
  42.     }
  43.     while(i1<t1)
  44.         a[k++] = b[i1++];
  45.     while(j1<t2)
  46.         a[k++] = c[j1++];
  47.  
  48.     free(b);
  49.     free(c);
  50.     print_array(a,7);
  51.     return inversion;
  52. }
  53. int SortandCount(int a[], int l, int r)
  54. {
  55.         int m;
  56.         int x,y,z;
  57.         if(l>=r)
  58.             return 0;
  59.         else {
  60.             m = (int)((l+r)/2);
  61.             x = SortandCount(a,l,m);
  62.             y = SortandCount(a,m+1,r);
  63.             z = MergeandCountSplitInv(a,l,m,r);
  64.         }
  65.         return x+y+z;
  66. }
  67. int main(int argc, char* argv)
  68. {
  69.         int a[] = { 2,7,6,3,4,5,1};
  70.                 int n = sizeof(a)/sizeof(int);
  71.         printf("%d\n",SortandCount(a,0,n-1));
  72.         system("pause");
  73.         return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement