Advertisement
Guest User

quicksort

a guest
Apr 10th, 2024
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. /*
  2.  *  base = base of the array
  3.  *  nitems = the number of items in the array
  4. *   size = size of an item
  5. *   *compar = comparator funcion (-1 if is < , 0 if equals , 1 if >)
  6. */
  7. void quick_sort(void *base, size_t nitems, size_t size, int (*comparator)(const void*, const void*)){
  8.     int low = 0;
  9.     int high = nitems-1;
  10.     //printf("%d test %d\n",low,high);
  11.     while(low<high){
  12.         int pi = partitioner(base + (size * (low)),high-low+1,size,comparator);
  13.        
  14.         quick_sort(base+ (size * (low)), pi-low,size,compar);
  15.         low = pi+1;
  16.     }
  17. }
  18.  
  19. size_t partitioner(void* base, size_t n_items, size_t sizeOfItem,int (*comparator)(const void*, const void*)){
  20.     void* pivot = base + (sizeOfItem * (n_items-1));
  21.  
  22.     int i = -1;
  23.     void* swap = malloc(sizeOfItem);
  24.     for(int j=0;j<n_items;j++){
  25.         if(((*comparator)(base+(j*sizeOfItem),pivot))<0){
  26.             ++i;
  27.             memcpy(swap, base + (i * sizeOfItem), sizeOfItem); //swap = base[i]
  28.             memcpy(base + (i * sizeOfItem), base + (j * sizeOfItem), sizeOfItem); // base[i] = base[j]
  29.             memcpy(base + (j * sizeOfItem), swap, sizeOfItem); //base[j] = swap
  30.         }
  31.     }
  32.     ++i;
  33.     memcpy(swap, pivot, sizeOfItem); //swap = pivot
  34.     memcpy(pivot, base + (i * sizeOfItem), sizeOfItem); //pivot = base[i]
  35.     memcpy(base + (i * sizeOfItem), swap, sizeOfItem);  //base[i] = swap
  36.     free(swap);
  37.     return i;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement