【问题标题】:In my c++ code of Bubble sort i have problem with my output when i give input in ascending order在我的 C++ 冒泡排序代码中,当我按升序输入输入时,我的输出出现问题
【发布时间】:2021-01-05 05:22:03
【问题描述】:

当我以降序输入(如4321)时它工作正常,但当我更改顺序时失败,即使是像1432 这样的一个位置

for(int pass = 1; pass <= n-1; pass++)
{   
    for(int j = 0; j < n-pass; j++)
    {
         if( a[j] > a[j+1])
            temp = a[j+1];
            a[j+1] = a[j];
            a[j] = temp;                    
    }   
}
    

输出

Enter the size of the array
4

Enter the elements of the array
1
4
3
2

Elements of the array are :
1432
Elements of the sorted array are :
0001

【问题讨论】:

  • 你缺少括号
  • 现在是学习的好时机:总是使用括号。即使是单行块。
  • @OP C++ 不是 Python。
  • 非常感谢您的帮助,我是初学者,我会学习
  • 你违反了 if 语句的基本结构,因为如果我们必须在 if 语句中执行多个语句,它需要括号!

标签: c++ bubble-sort


【解决方案1】:

你缺少括号。

默认情况下,if 的下一行被认为在范围内
如果你在 if 之后不加括号。

它导致了一些严重的错误 Apple Bug


for(int pass = 1; pass <= n-1; pass++)
{   
    for(int j = 0; j < n-pass; j++)
    {
         if( a[j] > a[j+1]) { // here
            temp = a[j+1];
            a[j+1] = a[j];
            a[j] = temp;     }       //here        
    }   
}

【讨论】:

  • 我建议你学习调试你的代码,找到一个好的IDE它会帮助你
【解决方案2】:

为 if 条件加上括号:

    if( a[j] > a[j+1]){
            temp = a[j+1];
            a[j+1] = a[j];
            a[j] = temp;  
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2018-05-24
    相关资源
    最近更新 更多