- Home /
 
Custom sorting function - need help
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?
Answer by Rabbit-Stew-dio · Mar 31, 2012 at 09:58 AM
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);
 
  
 
              I've never tried a list-array (or whatever you call it), but I'll give it a try. Thanks!
Hey, umm.. I hate to say, but it didn't work. I use javascript and it's complaining about the + sign. Wow.. I was just writing tons of code with no problems until I hit this. This sorting thing is confusing.
Still working with it though.. I took out that plus sign and the syntax errors went away.. I still can't make heads or tails on it though. Lots of debugging at this stage and have no idea how to use the list functions. :( Doesn't mean I can't learn..
Wow! Works excellent! Does exactly what I wanted. Thank you!
Answer by keld-oelykke · Mar 30, 2012 at 10:59 PM
 List<int> list = new List();
 // add numbers
 list.Sort(); // sorts ascending - this is what you need I guess
 list.Reverse(); // now descending
 
               Cheers, Keld
But that would leave the zeros at the top. I just want the zeros to stick at the bottom regardless of their value.
ok... wasn't sure how you wanted it sorted. You then also need the custom sort function as $$anonymous$$ suggests.
Your answer
 
             Follow this Question
Related Questions
Sort only considering last entry in my array 1 Answer
Sorting an Array of GameObjects by Name 1 Answer
Comparing Two Arrays 1 Answer
Working with Arrays for Custom Inspector 0 Answers
Creating A Basic Path For Enemies 1 Answer