Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array of Doubles with NaN in it

This is more of a 'Can you explain this' type of question than it is anything else.

I came across a problem at work where we were using NaN values in a table, but when the table was sorted, it came out in a very strange, strange manner. I figured NaN was mucking up something so I wrote up a test application to see if this is true. This is what I did.

static void Main(string[] args)
{
    double[] someArray = { 4.0, 2.0, double.NaN, 1.0, 5.0, 3.0, double.NaN, 10.0, 9.0, 8.0 };

    foreach (double db in someArray)
    {
        Console.WriteLine(db);
    }

    Array.Sort(someArray);
    Console.WriteLine("\n\n");
    foreach (double db in someArray)
    {
        Console.WriteLine(db);
    }

    Console.ReadLine();
}

Which gave the result:

Before:

4,2,NaN,1,5,3,NaN,10,9,8

After:

1,4,NaN,2,3,5,8,9,10,NaN

So yes, the NaN some how made the sorted array to be sorted in a strange way.

To quote Fry; "Why is those things?"

like image 690
Emmanuel F Avatar asked Feb 25 '11 23:02

Emmanuel F


1 Answers

I believe that's because

a < NaN == false
a > NaN == false
a == NaN == false

so the comparison on them breaks down, and that throws off the entire sort.

like image 110
corsiKa Avatar answered Oct 19 '22 23:10

corsiKa