简体   繁体   中英

Sort an array and return index of arrays according to elements size in c#

I need to sort the array from minimum to maximum value, but I need to return only the index of array after sorting it. I dont want to swap values, I just need to return the values index according to the value size, for eg

int[] arr = {7,8,2,3,1,5};
for (int i=0; i<=arr.length; i++)
{
   int index = Array.IndexOf(arr, i);
}

Now I want to return index of values from minimum to maximum as 4,2,3,5,0,1.

Your check in the for loop is wrong it should be i < arr.Length . For index you can do:

int[] arr = { 7, 8, 2, 3, 1, 5 };
int[] sortedIndexArray = arr.Select((r, i) => new { Value = r, Index = i })
                            .OrderBy(t => t.Value)
                            .Select(p => p.Index)
                            .ToArray();

For output:

foreach(int item in sortedIndexArray)
    Console.WriteLine(item);

Output:

4
2
3
5
0
1
var indexes = arr.Select((i, inx) => new { i, inx })
                  .OrderBy(x => x.i)
                  .Select(x => x.inx)
                  .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM