在C++中使用冒泡排序时出现意外值

Unexpected Value While using Bubble Sort in C++

本文关键字:意外 冒泡排序 C++      更新时间:2023-10-16

当使用气泡排序方法从最小到最大对数组进行排序时,它输出的意外值是:-858993460。

在调试器中,我被提示"围绕变量'numb 已损坏'的堆栈。

我目前正在使用Visual Studios来运行代码。

我还在新项目中运行了相同的代码,但没有结果。

#include <iostream>

int main()
{
int length = 6;   
int temp = 0;     
int end = 6;
int numb[] = { 6, 5, 4, 3, 2, 1 };
for (int counter = length - 1; counter > 0; counter--)
{
for (int i = 0; i < end; i++)
{
if (numb[i] > numb[i + 1])
{
temp = numb[i + 1];
numb[i + 1] = numb[i];
numb[i] = temp;
}
}
for (int i = 0; i <= 5; i++)
{
std::cout << numb[i] << " ";
}
std::cout << "n";
end--;
}
system("pause");
}

在你内部for循环中int i = 0; i < end; i++,你需要将条件设置为i < end - 1。这是因为在交换索引时,您已经与i + 1一起位于数组的末尾。