C ++冒泡排序:最大的数字变得随机

C++ Bubble Sort: Biggest number becomes random

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

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

我正在为每个 运行 打印出我自己的数组,以查看冒泡排序是如何工作的。

为什么最大的数字被切换到,在这种情况下,-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

您超出了数组的界限并在该数组之后交换了一个(未初始化的)值。请注意,您的数组包含 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;
            }
        }

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