【发布时间】: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;
}
输出:
【问题讨论】:
-
number[index+1] 跳过最大长度并访问内存中的无效/未初始化位置。现在你应该自己调试和修复简单的代码。
标签: c++ arrays sorting bubble-sort