【发布时间】:2014-09-21 00:25:37
【问题描述】:
我为整数创建了一个数组冒泡排序函数,该函数与正整数完美配合,但在使用负整数时会崩溃。初始显示功能有效,但随后就冻结了。我尝试了一个有符号的 int 数组,但无济于事。
我已经找遍了,但找不到其他人有这个确切的问题。
int defaultArray[6] = { 12, -5, 21, -1, 15, 17 };
int numElements = 6;
int lastSwap;
int searchEnd = numElements - 1;
bool sorted = false;
while (!sorted)
{
for (int i = 0; i < searchEnd; ++i)
{
// If the number in position i is larger than the number in the
// position i + 1 then swap them
if (defaultArray[i] > defaultArray[i + 1]) {
int temp = defaultArray[i];
defaultArray[i] = defaultArray[i + 1];
defaultArray[i + 1] = temp;
lastSwap = i + 1;
}
}
// If the lastSwap is at position one we can conclude that the array is
// sorted so if lastSwap isn't 1 move searchEnd and continue
if (lastSwap != 1)
{
// Conclude that from lastSwap to the end of the array is sorted
// searchEnd begins one position to the left of lastSwap
searchEnd = lastSwap - 1;
}
else {
sorted = true;
}
【问题讨论】:
-
你有点忘了描述问题。你只是说它“停止工作”。但是,这是什么意思?它会崩溃吗?它会永远循环吗?它会产生不正确的结果吗?
-
这里没有你所有的代码。你最初在哪里设置
lastSwap,你在你的(外)循环中设置在哪里? -
一方面,如果您的数组开始排序,lastSwap 保持未定义,searchEnd 也是如此。
标签: c++ arrays bubble-sort negative-number compare-and-swap