- Home /
How do I sort floats by highest to lowest value?
Say I have an array filled with times, but in seconds accurate down to the millisecond. How would I go about sorting these in order from highest to lowest value?
I have tried this method out: http://www.zparacha.com/sort_numeric_arrays/#.T2KysRFuksI
But, it only seems to sort intergers. I need it to sort down to the decimal.
Did you try that code you linked to? I don't think it would care if it were ints or floats
Yea.. it worked, but, for some reason, it rounded everything up. One thing I tried doing is multiplying by 10000 so that the decimal places would be counted for, but it's really a pain to do it that way.
Answer by rutter · Mar 16, 2012 at 10:16 PM
If you're not worried about the internals of the sort, letting the .NET framework take care of it for you may save some headaches. You didn't mention which particular data structure you're using, so I'll offer an example which includes some popular choices.
#pragma strict
import System.Collections.Generic;
//sort a built-in array of floats
var x = new float[3];
x[0] = 300.1;
x[1] = 200.2;
x[2] = 500.3;
System.Array.Sort(x);
//sort an Array() of floats
var y = new Array();
y.Push( 300.1 );
y.Push( 200.2 );
y.Push( 500.3 );
y.Sort();
//sort a .NET list of floats
var z = new List.<float>();
z.Add( 300.1 );
z.Add( 200.2 );
z.Add( 500.3 );
z.Sort();
//reverse our lists
System.Array.Reverse(x);
y.Reverse();
z.Reverse();
Whats a data structure?? I'm a javascript guy, so I'm a little confused.. $$anonymous$$y array already contains the floats. I just have to put them in a different order. I'm not seeing what you are doing with 300.1 or 200.2, because those should just already be in the array to start with. I have no idea what .Net, pragma strict, or import System Collections Generic even means. :/
It's just a simple array - 8 floats that are completely out of order. I am trying to judge a timed race where 8 cars each finish with a different time. The question is: who took first place, second place, third place.. etc. The times have to be put in order, and then I can say: if(myTime==finishedTime[1])me="first place";
See what I mean now? It shouldn't be so complicated. I just can't figure out why that example I linked to above rounds my floats up to the nearest whole number.