Qsort and Comparators have weird behavior. WITH

So, I use qsort in my C program from the C library. It works as expected, so I decided to play with comparators.

Comparator 1 (I use this):

 int compare (const void * a, const void * b)
{
  if (*(double*)a > *(double*)b) return 1;
  else if (*(double*)a < *(double*)b) return -1;
  else return 0;  
}

Comparator 2:

int comp (const void *a, const void *b)
{
    const double *ia = (const double *)a; // casting pointer types 
    const double *ib = (const double *)b;
    return *ia  - *ib; 
}

The first one works the way I want. The second should do the same first. I would like to use the second one, because the program works a little faster, but the fact that it really does not sort anything!

I'm sure I used comparator # 2 on smaller arrays and it worked. If I'm missing something there.

+4
source share
1 answer

The second should do the same first.

, , .

, , 5.3 4.9. , ; , , 0.4, int, qsort, 5.3 4.9 .

signum . , C ; . Q & A .

+7

Source: https://habr.com/ru/post/1672648/


All Articles