- Home /
help sorting an array
any idea how to sort an vector2d array (vector2 List) so that it starts with members (Vector2(x,y)) who have the lowest x?
Answer by Mike 3 · Nov 15, 2010 at 05:32 AM
Check the answers here:
http://answers.unity3d.com/questions/15280/sorting-builtin-arrays
Should be fairly simple to write the comparer to sort by the x value
Answer by dot · Nov 15, 2010 at 01:48 PM
ok, so for anybody out there, I did it like this:
function bubbleSort(array){
var continueSort = true;
if(array.Count >1){
while (continueSort){
for(var i=0;i<array.Count;i++)
{
for(var j=i+1;j<array.Count;j++)
{
if(array[i].x > array[j].x)
{
continueSort = true;
var leftMost=array[i];
array[i]=array[j];
array[j]=leftMost;
}
else continueSort = false;
}
}
}
}
}
Answer by Statement · Dec 23, 2010 at 01:15 AM
Given you use List<>, here's the simplest way(s) I can think of.
// C# Example using lambda list.Sort((leftMost, rightMost) => leftMost.x - rightMost.x);
// JS/C# Example using delegate list.Sort(ByVector2X);
ByVector2X must be specified, and here's my version of it:
// C# comparer method int ByVector2X(Vector2 leftMost, Vector2 rightMost) { return leftMost.x - rightMost.x; }
// JS comparer method function ByVector2X(leftMost : Vector2, rightMost : Vector2) : int { return leftMost.x - rightMost.x; }
Note that using delegates like that causes new instances to be created so it might be unwise to have such code in tight loops. Ins$$anonymous$$d you should store a reference to the delegate ByVector2X and reuse the reference over and over.
Your answer
Follow this Question
Related Questions
unity Vector2 problem 1 Answer
C# Point structure 1 Answer
Vector2 issue with .positon and .position.x accuracy 1 Answer
[C#] can someone give me a detailed explanation of lerp 1 Answer
Shift-Click on Scene View to add Vector2 0 Answers