Mistyisty
Mistyisty

Reputation: 123

How to BubbleSort an array in descending order?

private static double[] BubbleSortAscending(double[] numberArray)
{
    int arrayLength = numberArray.Length;

    for(int i = 0; i < arrayLength - 1; i++)
    {
        for(int j = 0; j < arrayLength - 1 - i; j++)
        {
            if(numberArray[j] > numberArray[j + 1])
            {
                double num = numberArray[j];
                numberArray[j] = numberArray[j + 1];
                numberArray[j + 1] = num;
            }
        }
    }
    return numberArray;
}

Hello, in the code above I have managed to make it so that it sorts an array in ascending order, however I am fully stuck and stumped on how to edit or change it to make it sort in descending order? Any help would be appreciated!

Thank you.

Upvotes: 0

Views: 2689

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

All you have to do if you want to reverse sorting (in descending instead of ascemding order) is to reverse the condition: < instead of >:

   ...
   if(numberArray[j] < numberArray[j + 1])
   ...

Upvotes: 2

Related Questions