Advertisement
SergioRP

Plotze - Insertion Sort

Oct 18th, 2016
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #define MAX 10000
  5.  
  6. int main()
  7. {
  8.     int i, a[MAX];
  9.  
  10.     for (i = 0; i < MAX; i++)
  11.         a[i] = rand() % MAX;
  12.  
  13.     for (i = 1; i < MAX; i++)
  14.         printf("%i ", a[i]);
  15.  
  16.     printf("\n", a[i]);
  17.  
  18.     clock_t start = clock();
  19.     clock_t end;
  20.  
  21.     insertion_sort(a, MAX);
  22.  
  23.     end = clock();
  24.     printf("%f", (double)(end - start));
  25.  
  26.     return 0;
  27. }
  28.  
  29. void insertion_sort(int a[], int size)
  30. {
  31.     int i, j, x;
  32.  
  33.     for (i = 1; i < size; i++)
  34.     {
  35.         x = a[i];
  36.         a[0] = x;
  37.         j = i;
  38.  
  39.         while (x < a[j-1])
  40.         {
  41.             a[j] = a[j-1];
  42.             j--;
  43.         }
  44.         a[j] = x;
  45.     }
  46.  
  47.     for (i = 1; i < size; i++)
  48.         printf("%i ", a[i]);
  49.  
  50.     printf("\n");
  51. }
  52.  
  53. void insertion_sort2(int a[], int size)
  54. {
  55.     int i, j, x;
  56.  
  57.     for (i = 1; i < size; i++)
  58.     {
  59.         x = a[i];
  60.         a[0] = x;
  61.         j = i;
  62.  
  63.         while (x > a[j-1])
  64.         {
  65.             a[j] = a[j-1];
  66.             j--;
  67.         }
  68.         a[j] = x;
  69.     }
  70.  
  71.     for (i = 1; i < size; i++)
  72.         printf("%i ", a[i]);
  73.  
  74.     printf("\n");
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement