How to BubbleSort an array in descending order?

天大地大妈咪最大 提交于 2020-12-14 23:34:11

问题


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.


回答1:


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])
   ...


来源:https://stackoverflow.com/questions/51499930/how-to-bubblesort-an-array-in-descending-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!