gpt4 book ai didi

C++ 冒泡排序 : Biggest number becomes random

转载 作者:行者123 更新时间:2023-11-28 05:16:23 25 4
gpt4 key购买 nike

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

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

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

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

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

关于C++ 冒泡排序 : Biggest number becomes random,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com