RyanD96 February 2016
### Sorting positive NaN's and negative NaN's in a vector

I am attempting to create a program using a bubble sort in c++, i have to include positive and negative NaNs and sort them,I have got to the point where my program will sort negative to positive in ascending order including -0 and 0 but i am stuck on making it so that the NaNs are not mixed up.

How would i go about sorting these NaNs, possibly with the -Nans on the LHS of the integers and the NaNs on the RHS?

You can use `isnan`

to detect NaN and `signbit`

to check its sign. You can use `signbit`

to distinguish between positive and negative 0 too.

You will need to make a custom comparator to actually do sorting.

Comparator example:

```
bool double_order(double lhs, double rhs)
{
if(std::isnan(lhs)) {
if(std::signbit(lhs)) //Negative NaN is less than anything
return not (std::isnan(rhs) && std::signbit(rhs)); //Except another -NaN
else
return false; //Positive NaN are never less than anything
}
if(std::isnan(rhs))
if(std::signbit(rhs)) //Negative nans are tot larger than anything
return false;
else //Positive NaN are larger than anything
return true; //Except other +NaN, which is covered earlier
if(lhs == 0.0 && rhs == 0.0) //If both operands are 0, check for ±0
return std::signbit(lhs) > std::signbit(rhs); //signbit of negative is true
return lhs < rhs; //Otherwise do normal comparison (covers infinities)
}
```

Asked in February 2016

Viewed 3,182 times

Voted 10

Answered 1 times

Viewed 3,182 times

Voted 10

Answered 1 times