### Author Topic: qsort with NaN  (Read 3047 times)

#### Alessio

• Guest
##### qsort with NaN
« 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!

#### JohnF

• Guest
##### Re: qsort with NaN
« Reply #1 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

#### Alessio

• Guest
##### Re: qsort with NaN
« Reply #2 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; }}`

#### JohnF

• Guest
##### Re: qsort with NaN
« Reply #3 on: May 08, 2008, 11:26:50 am »
Ok, fine. If that works for you.

John