Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Sorting a list of Vector2 grid positions horizontally first ?

Discussion in 'Scripting' started by TheCelt, Apr 3, 2017.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    724
    Hello

    I am wondering how do you sort a list along the x axis before the y axis for a list ? I know it can be done using LINQ but it adds to the garbage collection and i would like to avoid that and use a raw C# code version that i can refer back to know how its done. I tried thinking about how to do it but couldn't work out how to loop multiple times through the list if that made any sense?

    The idea for the listed output would be like:

    1,0
    2,0
    1,1
    2,1

    And so on. So x first then y.
     
  2. Aldo

    Aldo

    Joined:
    Aug 10, 2012
    Posts:
    173
  3. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    724
    I haven't taken computer science but i presume quick sort is the fastest option since it has the word quick in the name ? What i was wondering though, how do you recursively run through partitions? I understand the logic of how to split the list from low to high but don't know how to do it recursively in C#.
     
  4. Aldo

    Aldo

    Joined:
    Aug 10, 2012
    Posts:
    173
    oh ok,
    first, quick sort is great but it's not the best all the time.
    since you are new to coding I would make something straight forward.

    first your array of vector2 (Vector2[]) and a second array of the same lenght.

    Then I would run a loop that will loop all the array and search for the "smallest" one, once you find it run it again but now for the second number, it's slow, not the best but it's easy to implement

    Code (CSharp):
    1. Vector2 somethingHigh = Vector2.one*1000000;
    2.   for(int h = 0; h<myArray.length; h++)
    3.   {
    4.     for(int i = h; i<myArray.length; i++)
    5.     {
    6.       if(myArray[i].x < somethingHigh.x && y < y)
    7.         somethingHigh = myarray[i];
    8.     }
    9.  
    10.     secondArray[h] = somethingHigh;
    11.   }
    12.