[英]C++ Bubble Sort Negative Numbers
我为整数创建了一个数组冒泡排序函数,该函数可以与正整数完美配合,但是当使用负整数时会崩溃。 初始显示功能有效,但随后冻结。 我试过一个有符号的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;
}
您正在尝试通过减少searchEnd
来优化算法,但我认为存在问题。 我建议您保持searchEnd
不变。 要确定数组是否已排序,请将sorted
设置为true,并设置while循环的开始,如果发生交换,则将其更改为false。 例如:
while (!sorted) {
sorted = true;
for (int i = 0; i < searchEnd; ++i) {
if (defaultArray[i] > defaultArray[i + 1]) {
// swap
sorted = false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.