Sorting an array starting from given index
Hello, i have an array of Vector3 with 6 elements, let
Vector3[] array = new Vector3[]
{
zero,one,two,three,four,five
};
A certain method gives me back one of those Vectors, let#s assume in this case "three".
I´d like to re-sort this array in new one to have something like:
Vector3[] newArray = new Vector3
{
three, four, five, zero, one, two
};
What's the best way? Thanks!
Comment
Best Answer
Answer by dkjunior · Oct 14, 2015 at 05:04 PM
I assume you don't actually need to sort the array, you just need to shift it circularly?
If so, this method should do it:
public Vector3[] ShiftArray(Vector3[] array, Vector3 firstElement)
{
int firstElementIndex = Array.IndexOf(array, firstElement);
if(firstElementIndex == -1)
{
Debug.LogError("Requested element not found");
return null;
}
Vector3[] newArray = new Vector3[array.Length];
for(int i = 0; i < array.Length; i++)
{
newArray[i] = array[(firstElementIndex + i) % array.Length];
}
return newArray;
}
wonderful solution, thanks a lot. You unblocked a huge problem here.
Your answer
