user3411282
user3411282

Reputation: 63

Calling qsort comparator

I have a comparator function that returns 1, 0, or -1, declared as follows:

int multiPrecisionCompare(const DIGIT_T a[], const DIGIT_T b[], int32_t length); 

where DIGIT_T is int8_t.

I want to call a function qsort but I have a problem understanding what I have to change or how to call the comparator function inside.

qsort(bigArray->x, 8,30 , <-what here?????->);


    i

int multiprecisionCompare(const DIGIT_T a[], const DIGIT_T b[], int32t length) 
{
  while(length--) { // little endian
if(a[length] > b[length])
  return 1;
if(a[length] < b[length])
  return -1;
}

return 0;
}


point * bigArray = (point *)(malloc(K*sizeof(point)));
CreateListAndOrder( lots of parameters) // this fills the bigArray unsorted
/* point is a structure of X,Y,Z where each of this is DIGIT_T */
qsort((void *)bigArray, K, sizeof(point), cmp);

I want to sort it according to X coordinate, but that is solved by int32t length, that it should compare only first coordinate from that struct

int cmp(const void *a, const void *b){
    return multiPrecisionCompare((const DIGIT_T*)a, (const DIGIT_T*)b,  DIGIT_LENGTH);
    //return multiPrecisionCompare(*(const DIGIT_T**)a, *(const DIGIT_T**)b,  DIGIT_LENGTH);
}

Upvotes: 0

Views: 240

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

int multiPrecisionCompare(const DIGIT_T a[], const DIGIT_T b[], int32_t length);
int32_t DIGIT_LENGTH;
int cmp(const void *a, const void *b){
    return multiPrecisionCompare(((point*)a)->x, ((point*)b)->x, DIGIT_LENGTH);
}

DIGIT_LENGTH = length;
point * bigArray = (point *)malloc(K*sizeof(point));
//fills the bigArray unsorted
qsort(bigArray, K, sizeof(point), cmp);

Upvotes: 1

GMichael
GMichael

Reputation: 2776

Here is an example:

int cmpfunc (const void * a, const void * b)
{
   return ( *(DIGIT_T *)a - *(DIGIT_T *)b );
}

qsort(bigArray->x, 8, 30 , cmpfunc);

Upvotes: 1

Leandros
Leandros

Reputation: 16825

qsort accepts a pointer to a function with the following signature:

int cmp(void const *, void const *)

You have to adjust your comparison function, to match this signature, and than simply pass in a function pointer.

Upvotes: 2

Related Questions