Sorting an array of Doubles with NaN in it
- by Agent Worm
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?"