Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * base = base of the array
- * nitems = the number of items in the array
- * size = size of an item
- * *compar = comparator funcion (-1 if is < , 0 if equals , 1 if >)
- */
- void quick_sort(void *base, size_t nitems, size_t size, int (*comparator)(const void*, const void*)){
- int low = 0;
- int high = nitems-1;
- //printf("%d test %d\n",low,high);
- while(low<high){
- int pi = partitioner(base + (size * (low)),high-low+1,size,comparator);
- quick_sort(base+ (size * (low)), pi-low,size,compar);
- low = pi+1;
- }
- }
- size_t partitioner(void* base, size_t n_items, size_t sizeOfItem,int (*comparator)(const void*, const void*)){
- void* pivot = base + (sizeOfItem * (n_items-1));
- int i = -1;
- void* swap = malloc(sizeOfItem);
- for(int j=0;j<n_items;j++){
- if(((*comparator)(base+(j*sizeOfItem),pivot))<0){
- ++i;
- memcpy(swap, base + (i * sizeOfItem), sizeOfItem); //swap = base[i]
- memcpy(base + (i * sizeOfItem), base + (j * sizeOfItem), sizeOfItem); // base[i] = base[j]
- memcpy(base + (j * sizeOfItem), swap, sizeOfItem); //base[j] = swap
- }
- }
- ++i;
- memcpy(swap, pivot, sizeOfItem); //swap = pivot
- memcpy(pivot, base + (i * sizeOfItem), sizeOfItem); //pivot = base[i]
- memcpy(base + (i * sizeOfItem), swap, sizeOfItem); //base[i] = swap
- free(swap);
- return i;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement