0
我为整数创建了一个数组冒泡排序函数,它与正整数完美协作,但是当使用负整数时会崩溃。初始显示功能可以工作,但只会冻结。我试过一个signed int数组无效。C++ Bubble Sort Negative Numbers
我已经看了所有,但无法找到任何其他人与这个确切的问题。
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;
}
你有点忘了描述问题。你只是说它“停止工作”。但是,这是什么意思?它会崩溃吗?它会永久循环吗?它会产生不正确的结果吗? – 2014-09-21 00:33:24
这里没有你所有的代码。你最初在哪里设置'lastSwap',你在哪里设置你的(外部)循环? – 2014-09-21 00:44:03
有一件事,如果你的数组开始排序,lastSwap仍然未定义,searchEnd也是如此。 – dhavenith 2014-09-21 00:44:45