Pelles C forum

C language => Expert questions => Topic started by: Alessio on May 07, 2008, 10:23:37 AM

Title: qsort with NaN
Post by: Alessio on May 07, 2008, 10:23:37 AM
Hi,

I've an array with some values and NaNs.

How can I use qsort that NaN entries are moved to the end of the sorted array ?

Thanks!
Title: Re: qsort with NaN
Post by: JohnF on May 08, 2008, 09:11:53 AM
You need to create a function that compares the floats and returns a specific value depending on your criteria.

How would you normally compare for a NAN ?

John
Title: Re: qsort with NaN
Post by: Alessio on May 08, 2008, 11:00:19 AM
A way to do it:

Code: [Select]
int compare(const void *a, const void *b)
{
float arg1 = *((float *)a);
float arg2 = *((float *)b);

if ( isnan(arg1) && isnan(arg2) )
{
return 0;
}
else if ( isnan(arg1) )
{
return 1;
}
else if ( isnan(arg2) )
{
return -1;
}
else if ( arg1 < arg2 )
{
return -1;
}
else if ( arg1 == arg2 )
{
return 0;
}
else
{
return 1;
}
}
Title: Re: qsort with NaN
Post by: JohnF on May 08, 2008, 11:26:50 AM
Ok, fine. If that works for you.

John