Search code examples
c++arraysbubble-sortnegative-numbercompare-and-swap

C++ Bubble Sort Negative Numbers


I created a array bubble sort function for integers that works perfectly with positive integers but it crashes when negative integers are used. The initial display function works but then it just freezes. I have tried a signed int array to no avail.

I have looked all over but can't find anyone else with this exact problem.

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

Solution

  • You are trying to optimize your algorithm decreasing searchEnd, and I think that there is the problem. I recommend you to keep searchEnd the same. To determine if the array is sorted, set sorted to true and the start of the while loop and change it to false if a swap occurs. For example:

    while (!sorted) {
        sorted = true;
        for (int i = 0; i < searchEnd; ++i) {
            if (defaultArray[i] > defaultArray[i + 1]) {
                // swap
                sorted = false;
            }
        }
    }