Advertisement
GeeckoDev

generic insertion sort

Oct 25th, 2011
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.87 KB | None | 0 0
  1. // Generic insertion sort
  2. // Can be compiled using : -W -Wall -Werror -Wextra -ansi -pedantic
  3.  
  4. void sort(void *p, int n, int size, int cmp(void *, void *))
  5. {
  6.   int i;
  7.   int j;
  8.   void *a;
  9.   a = __builtin_malloc(size);
  10.    
  11.   for (i=1; i<n; i++)
  12.   {
  13.     __builtin_memcpy(a, (char*)p+i*size, size);
  14.    
  15.     for (j=i; j>0 && cmp((char*)p+(j-1)*size, a)>0; j--)
  16.     {
  17.       __builtin_memcpy((char*)p+j*size, (char*)p+(j-1)*size, size);
  18.     }
  19.    
  20.     __builtin_memcpy((char*)p+j*size, a, size);
  21.   }
  22.    
  23.   __builtin_free(a);
  24. }
  25.  
  26.  
  27. int compare(void *a, void *b)
  28. {
  29.   return *((int*)a) - *((int*)b);
  30. }
  31.  
  32. #include <stdio.h>
  33.  
  34. int main()
  35. {
  36.   int tab[5] = {2,986,-9,0,16};
  37.   printf("%d %d %d %d %d\n", tab[0], tab[1], tab[2], tab[3], tab[4]);
  38.   sort(tab, 5, sizeof(int), compare);
  39.   printf("%d %d %d %d %d\n", tab[0], tab[1], tab[2], tab[3], tab[4]);
  40.   return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement