C++冒泡排序负数

C++ Bubble Sort Negative Numbers

本文关键字:冒泡排序 C++      更新时间:2023-10-16

我为整数创建了一个数组气泡排序函数,它与正整数完美配合,但在使用负整数时会崩溃。最初的显示功能可以工作,但随后它就冻结了。我尝试过一个带符号的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;
        }
    }
}