【问题标题】:How to BubbleSort an array in descending order?如何按降序对数组进行冒泡排序?
【发布时间】:2019-01-01 03:40:51
【问题描述】:
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;
}

您好,在上面的代码中,我设法使它按 升序 顺序对数组进行排序,但是我完全被困在如何编辑上或更改它以使其按降序顺序排序?任何帮助将不胜感激!

谢谢。

【问题讨论】:

  • 反向条件:if(numberArray[j] &lt; numberArray[j + 1])
  • 不是最有效的解决方案:只需在最后反转您的数组
  • 这能回答你的问题吗? Bubble sort strings in descending order

标签: c# sorting bubble-sort descendant


【解决方案1】:

如果你想reverse 排序(以descending 而不是ascemding 的顺序)你所要做的就是reverse 条件:&lt; 而不是 &gt;:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-03
    • 2021-04-26
    • 2017-04-24
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    相关资源
    最近更新 更多