C ++冒泡排序负数

时间:2014-09-21 00:25:38

标签: c++ arrays bubble-sort negative-number compare-and-swap

我为整数创建了一个数组冒泡排序函数,它与正整数完美匹配,但在使用负整数时会崩溃。初始显示功能有效,但它只是冻结。我试过一个签名的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;
        }

1 个答案:

答案 0 :(得分:1)

您正在尝试优化算法,减少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;
        }
    }
}