Hi, I’m trying to sort an array of intergers that looks somewhat like this:
[-650,-750,-820,-960,-460,-660,-990,0,0,0,0]
This is my sorting function:
function compare(a,b){
return a-b;
}
I want it to put the highest number on top, but the zeros on the bottom of the array. Does anyone know how I can get it to do that?
Use a smarter Compare function:
function compare(a: int,b: int)
{
if (a == b) return 0;
if (a == 0) return +1;
if (b == 0) return -1;
// otherwise compare normally
return a-b;
}
And then sort the list. You will have to use the list from the System.Collection.Generic namespace. You cannot use the Unity-Array class, as it lacks a customizable sort operation.
List<int> yourlist;
yourlist.Sort(Compare);
List list = new List();
// add numbers
list.Sort(); // sorts ascending - this is what you need I guess
list.Reverse(); // now descending
Cheers, Keld