0

I have four arrays array_1, array_2, array_3, array_4.

array_2,array_3,array_4 shall be sorted according to array_1.

When I just sort array_2 according to array_1 it is working.

 Array.Sort(array_1, array_2);

But when I try this just array_2 is being sorted (or just the array that is sorted in the first line). array_3 and array_4 remain the same.

 Array.Sort(array_1, array_2);
 Array.Sort(array_1, array_3);
 Array.Sort(array_1, array_4);

Is there a possibility to sort multiple arrays according to one reference array, at the same time?

Mdarende
  • 469
  • 3
  • 13

1 Answers1

1

According to the documentation ( https://learn.microsoft.com/en-us/dotnet/api/system.array.sort?view=net-7.0#system-array-sort(system-array-system-array) at "Remarks")

Each key in the keys Array has a corresponding item in the items Array. When a key is repositioned during the sorting, the corresponding item in the items Array is similarly repositioned.

The main keyword here is "when", so only when a item of array_1 is repositioned will it effect the second array, therefor if array_1 is already sorted, nothing will happen to the second array.

array_1 gets sorted on the first call to Array.Sort(array_1, array_2);

There for either assume that array_1 is unsorted and use .Clone() to create copy of the array, where Array.Sort will only sort the copy of the original unsorted array, or manually shuffle it prior to sorting the other arrays.

so instead of

Array.Sort(array_1, array_2);

use

Array.Sort((Array)array_1.Clone(), array_2);

See a demo here:

https://dotnetfiddle.net/b1XkrQ

or if you can't quarantee it is unsorted, shuffle array_1 prior to calling sort, here you may find implementation of shuffle Best way to randomize an array with .NET

Rand Random
  • 7,300
  • 10
  • 40
  • 88