Home > Software design >  How to get index of all values of not sorted array based on lower value C#
How to get index of all values of not sorted array based on lower value C#

Time:07-31

I am currently working on a simulation system so i've an array like

int[] arr = {2,5,9,10,0, 4,1,5,3};

I want array of indexes of values based on lower and output result like

result = {4, 6, 0, 8, 1, 7, 2, 3};

I searched all over for almost 3 days i can't find.

CodePudding user response:

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();

CodePudding user response:

We can use the built-in Array.Sort() method. It has a second parameter that returns the sorted indices as well, but it requires us to make a new array with the indices (i.e. starts from 0 and ends at the length of the original array)

int[] arr = {2,5,9,10,0,4,1,5,3};
int[] indexArr = Enumerable.Range(0, arr.Length).ToArray();
Array.Sort(arr, indexArr);

Note that you will need to add using System.Linq; if you get an error that Enumerable doesn't exist.

  • Related