C++冒泡排序负数
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;
}
}
}
相关文章:
- 如何在C++中对数组进行冒泡排序
- 我想在 c++ 中对单向链表进行冒泡排序,但我一直面临左值错误,无法解决它
- 在C++中使用冒泡排序时出现意外值
- 冒泡排序中所需的交换次数,而无需实际对其进行排序
- 如何对文件中数组中的单个列进行冒泡排序?C++
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- 冒泡排序无法对C++中的对象的动态数组进行排序
- 冒泡排序.C++
- 链表的冒泡排序
- 有没有选择排序优于冒泡排序的输入
- C++:如何使用冒泡排序来重新排列我的数据
- 冒泡排序随机数
- 矢量下标超出范围-冒泡排序
- 使用冒泡排序比较类对象
- 在c++中使用冒泡排序/交换对字符串进行排序
- 矢量下标超出范围错误,C++,冒泡排序
- 冒泡排序、选择排序和插入排序
- 使用冒泡排序c++对结构数组的成员进行优先级排序
- 冒泡排序链表C++
- 行搜索和冒泡排序的问题