0

I am trying to write a function that takes array like this [4,7,2,1,9] then return another array like this

[4,1,0,2,3]// the sorted indices descending for the input array values

I've tried this code but it isn't working properly, I want to hepl me for writing a function that sort array like this with minimum cost

 public void solution(int[] D)
 {
    int[] sorted = new int[D.Length];

    for (int i = 0; i < D.Length; i++)
    {
        int ind = 0;

        for (int j = 0; j < D.Length; j++)
        {
            if (D[j] > D[i] ) //&&
            {
                ind = j;
            }
        }
        sorted[i] = ind;
    }
}
0

1 Answer 1

4

Array.Sort allows you to pass a second array:

var data = new[] { 4, 7, 2, 1, 9 };
var indices = new[] { 0, 1, 2, 3, 4 };
Array.Sort( data, indices );

If you need it in descending order, use Array.Reverse or pass it an IComparer that swaps the order:

class ReverseSort : IComparer<int>
{
    public int Compare( int x, int y )
    {
        return y.CompareTo( x );
    }
}

Array.Sort( data, indices, new ReverseSort() );

Unfortunately Array.Sort doesn't have a nice overload that takes two arrays + a delegate like the other overloads do.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.