在 C++ 中使用冒泡排序时出现意外值
Unexpected Value While using Bubble Sort in C++
当使用冒泡排序方法将我的数组从最小到最大排序时,它输出了一个意外值:-858993460。
在调试器中,系统提示我“Stack around variable 'numb was corrupted'。
我目前正在使用 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
了。
当使用冒泡排序方法将我的数组从最小到最大排序时,它输出了一个意外值:-858993460。
在调试器中,系统提示我“Stack around variable 'numb was corrupted'。
我目前正在使用 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
了。