Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array.Sort is changing unspecified arrays in unity

I am trying to sort an array, and a list of indices, but I want the original array to stay the same.

When I use the Array.Sort() function, it not only sorts the specified arrays, but also the fitnessVals array (see code below). Does anyone know why this is, and what I can do to stop it from happening?

My code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        tempFitnessVals = new float[numberOfItems];
        tempFitnessVals = fitnessVals;
        int[] indexes = new int[tempFitnessVals.Length];
        for (int i = 0; i < indexes.Length; i++)
        {
            indexes[i] = i;
        }
        Array.Sort(tempFitnessVals, indexes);
        Array.Reverse(tempFitnessVals);
        Array.Reverse(indexes);

>Solution :

The following code makes a reference and causes the issue you are facing:

tempFitnessVals = fitnessVals;

You need to replace this line with Array.Copy:

...
Array.Copy(fitnessVals, tempFitnessVals, numberOfItems);
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading