【问题标题】:C++ Bubble Sort: Biggest number becomes randomC++ 冒泡排序:最大的数字变成随机的
【发布时间】:2017-07-22 11:50:28
【问题描述】:

我正在处理一项学校作业,任务是按升序对数组进行排序。我遇到了冒泡排序的麻烦。当数组开始排序时,它会排序,但数组的最大整数会切换为随机整数。

不要介意选择变量和输入。该任务应该可以选择是升序还是降序。在这段代码中,我只达到了升序排序。

我正在为我自己的每次运行打印出数组,以查看冒泡排序的工作原理。

为什么要切换到最大的数字,在这种情况下是 -13248? 如果这是任何人都知道的好信息,请使用 cygwin 编译器。

int main()
{
    int number[] = {900,800,700,697,512,455,318,217,143,32};
    int swapHolder = -1;
    int end = 10;
    int length = 10;
    string choice;

    cout << "This is an array of ten integers." << endl;

    for(int i=0; i<10; i++)
    {
        cout << number[i] << ", ";
    }
    cout << endl;

    cout << "Choose whether you want to sort the array in ascending or descending order." << endl;
    cout << "Type ASC for ascending or DESC for descending." << endl;
    cin >> choice;

    if(choice == "ASC")
    {
        for(int counter = length - 1; counter >= 0; counter--)
        {
            for(int index = 0; index < end; index++)
            {
                if (number[index] > number[index+1])
                {
                    swapHolder = number[index+1];
                    number[index+1] = number[index];
                    number[index] = swapHolder;
                }
            }
            for(int index = 0; index < 10; index++)
                {
                    cout << number[index] << ", ";
                }
            cout << endl;
            end--;
        }
    }
    return 0;
}

输出:

output from cmd

【问题讨论】:

  • number[index+1] 跳过最大长度并访问内存中的无效/未初始化位置。现在你应该自己调试和修复简单的代码。

标签: c++ arrays sorting bubble-sort


【解决方案1】:

您超出了数组的边界,并在该数组之后立即交换了一个(未初始化的)值。请注意,您的数组包含 10 个元素,即 0..9,并且不允许访问 number[10]。在您的代码中index 运行到9,然后您访问number[index+1],这实际上意味着number[10] 然后:

        int end = 10;
        for(int index = 0; index < end; index++)
        {
            if (number[index] > number[index+1])
            {
                swapHolder = number[index+1];
                number[index+1] = number[index];
                number[index] = swapHolder;
            }
        }

虽然实际上是未定义的行为,但常见的行为是程序要么崩溃,要么访问(并使用)尚未初始化的内存,因此包含一些“随机”值,例如-13248.

【讨论】:

  • 啊,好吧,就这么简单,呵呵。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 2016-09-19
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
相关资源
最近更新 更多