Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 7th, 2012  |  syntax: None  |  size: 1.51 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.  
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <malloc.h>
  5.  
  6. static void
  7. dump_intv (int *intv,
  8.            int  count)
  9. {
  10.     int i;
  11.     for (i = 0; i < count; i++) {
  12.         printf("%d ", intv[i]);
  13.     }
  14. }
  15.  
  16. static void
  17. swap (int *a,
  18.       int *b)
  19. {
  20.     int tmp = *a;
  21.     *a = *b;
  22.     *b = tmp;
  23. }
  24.  
  25. static void
  26. mergesort (int *intv,
  27.            int  count)
  28. {
  29.     if (count == 2) {
  30.         if (intv[0] > intv[1])
  31.             swap (&intv[0], &intv[1]);
  32.     } else if (count > 2) {
  33.         int halfcount, ibm;
  34.         int ia, ib;
  35.         int *a, *b;
  36.         int *tmp;
  37.  
  38.         halfcount = count / 2;
  39.  
  40.         tmp = malloc (sizeof (int) * count);
  41.         memcpy (tmp, intv, sizeof (int) * count);
  42.  
  43.         a = &tmp[0];
  44.         b = &tmp[halfcount];
  45.  
  46.         ibm = halfcount;
  47.         if (count % 2)
  48.             ++ibm;
  49.  
  50.         mergesort (a, halfcount);
  51.         mergesort (b, ibm);
  52.  
  53.         ia = ib = 0;
  54.         while (ia < halfcount && ib < ibm) {
  55.             if (*a < *b)
  56.                 intv[(ia++)+ib] = *a++;
  57.             else
  58.                 intv[ia+(ib++)] = *b++;
  59.         }
  60.  
  61.         while (ia < halfcount)
  62.             intv[(ia++)+ib] = *a++;
  63.  
  64.         while (ib < ibm)
  65.             intv[ia+(ib++)] = *b++;
  66.  
  67.         free (tmp);
  68.     }
  69. }
  70.  
  71. int
  72. main (int    argc,
  73.       char **argv)
  74. {
  75.     int i;
  76.     int *numbers;
  77.  
  78.     argc --;
  79.     argv ++;
  80.  
  81.     numbers = malloc (sizeof (int) * argc);
  82.  
  83.     for (i = 0; i < argc; i++) {
  84.         numbers[i] = atoi(argv[i]);
  85.     }
  86.  
  87.     mergesort (numbers, argc);
  88.     dump_intv (numbers, argc);
  89.     printf ("\n");
  90.  
  91.     return 0;
  92. }