In the 2nd array you want the indexes of the elements in the first array as sorted in ascending order.
You can use LINQ to do this
int[] arr = { 2, 5, 9, 10, 0, 4, 1, 5, 3 };
int[] result = arr.Select((x, i) => (x, i))
.OrderBy(t => t.x)
.Select(t => t.i)
.ToArray();
Here, we used an overload of Select
that yields the index:
Select<TSource,TResult>(IEnumerable, Func<TSource,Int32,TResult>).
The first Select
creates a ValueTuple.
The test
Console.WriteLine(String.Join(", ", result));
Yields the result:
4, 6, 0, 8, 5, 1, 7, 2, 3
Note that the number 5
appears twice in the input array. Therefore, the result is ambiguous. (Your expected result has only 8 indexes but the input array has a length of 9)
My full .NET 6.0 test code (Console App):
namespace CoreConsoleApp;
internal static class SortedArrayIndexes
{
public static void Test()
{
// Indexes 0 1 2 3 4 5 6 7 8
int[] arr = { 2, 5, 9, 10, 0, 4, 1, 5, 3 };
int[] result = arr.Select((x, i) => (x, i))
.OrderBy(t => t.x)
.Select(t => t.i)
.ToArray();
Console.WriteLine(String.Join(", ", result));
}
}
It is called in my Main
method with:
SortedArrayIndexes.Test();
Console.ReadKey();
In case you are working with an older Framework or language version, you can also use the older System.Tuple Class
int[] result = arr.Select((x, i) => new Tuple<int, int>(x, i))
.OrderBy(t => t.Item1)
.Select(t => t.Item2)
.ToArray();