1

Can anybody tell me how can i sort elements of an integer array in descending order? is it possible?

thank you

2
  • 1
    Why do you think it isn't possible ? Have you googled on the question regarding the ways of doing it? Commented Mar 8, 2011 at 19:48
  • 3
    Is this homework? What have you tried already? Did you search? Commented Mar 8, 2011 at 19:48

7 Answers 7

4

To sort it in-place, you can use the overload that accepts a comparison delegate:

Array.Sort(arr, (x,y)=>y.Compare(x));
Sign up to request clarification or add additional context in comments.

Comments

2

Use Array.Sort:

Array.Sort(myArray, (a, b) => b.Compare(a));

Comments

1
myIntArray = myIntArray.OrderBy(i => -1 * i).ToArray();

or

myIntArray = myIntArray.OrderByDescending(i => i).ToArray();

or

Array.Sort(myIntArray, (x,y) => x.Compare(y) * -1);

Comments

1

Use Sort() followed by Reverse()

3 Comments

Though this works, there are sorting overloads that don't require reversing.
My intention with this answer was to provide the simplest (but not best) solution. The OP was asking such a basic question that I was afraid to throw lambdas into the mix.
Although I know that efficiency isn't really a concern in this particular instance, it's interesting to note that for primitive types, Sort() followed by Reverse() will execute almost three times as fast as calling Sort with a comparison delegate. See informit.com/guides/content.aspx?g=dotnet&seqNum=781 for the reasons why.
1

This may help if you have a class assignment and your professor doesn't want you to use Array.Sort.

private void button1_Click(object sender, EventArgs e)
{
    int[] numbers = { 7, 4, 2, 6, 1, 10, 5, 8, 9, 3 };
    SortArray(numbers);
    foreach (int n in numbers)
    {
        textBox1.Text = textBox1.Text + n.ToString() + ' ';
    }
}

public static void SortArray(int[] num)
{
    int temp;
    int count = 0;

    while (count < num.Length - 1)
    {
        int min = num[count];

        for (int x = count; x < num.Length; x++)
        {
            if (min > num[x])
            {
                temp = num[count];
                min = num[x];
                num[count] = num[x];
                num[x] = temp;

            }

        }

        count++;
    }
}   

Comments

0
Array.Sort(arr, (num1,num2) => num1.Compare(num2));

Comments

0

Try the following:

Array.Sort(array, (x, y) => y.Compare(x));

Comments

Your Answer

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