簡體   English   中英

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;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM