为什么我的冒泡排序会忽略最后一个变量?c ++

时间:2014-08-26 01:32:27

标签: c++ sorting variables

出于某种原因,每当我为我的代码选择随机变量时,我会得到一个数字,直到冒泡冒号排序结束。

#include <iostream>
using namespace std;

int main() 
{
    int a, b, c, d, e, hold;

    cout << "Input 5 integers for sorting, press enter after each number.\n";
    cin >> a >> b >> c >> d >> e;

    for (int i = 0; i < 5; i++)//runs the sequence 5 times to match the number of variables.
    {
        hold = a;
        if (b < hold) 
           {
                 hold = b;
                 b = a;
                 a = hold;
            }
        if (c < hold) 
           {
                 hold = c;
                 c = b;
                 b = hold;
           }
        if (d < hold) 
           {
                 hold = d;
                 d = c;
                 c = hold;
           }
        if (e < hold) 
           {
                 hold = e;
                 e = d;
                 d = hold;
           }

        cout << "The smallest number was " << a << " " << b << " " << c << " " << d << " " << e << endl;
    }

    return 0;
}

数字为98,45,65,12和32,我最后的两个结果是12,45,98,65,32。

编辑:我不知道在将代码复制到帖子时我做了什么,但这不是我在编译器中看到的。对不起弄乱了。

1 个答案:

答案 0 :(得分:0)

您的冒泡排序中的错误是在交换后的比较中。 在比较b&lt;保持和交换,您的保留包含前一个数字值,因此您使用错误的数字进行比较。 在你的情况下,没有必要使用hold进行比较,而只是比较b&lt; a,c&lt; b等等。

    if (b < a) {
        hold = b;
        b = a;
        a = hold;
    }
    if (c < b) {
        hold = c;
        c = b;
        b = hold;
    }
    if (d < c) {
        hold = d;
        d = c;
        c = hold;
    }
    if (e < d) {
        hold = e;
        e = d;
        d = hold;
    }