Search code examples
c++arrayssortingbubble-sort

Unexpected Value While using Bubble Sort in C++


When using the bubble sort method to sort my array from smallest to largest its outputting an unexpected value of: -858993460.

Within the debugger i'm being prompted with "Stack around variable 'numb was corrupted'.

I'm currently using Visual studios to run the code.

I have also ran the same code within a new project with no results.

#include <iostream>


int main()
{
    int length = 6;   
    int temp = 0;     
    int end = 6;
    int numb[] = { 6, 5, 4, 3, 2, 1 };

    for (int counter = length - 1; counter > 0; counter--)
    {
        for (int i = 0; i < end; i++)
        {
            if (numb[i] > numb[i + 1])
            {
                temp = numb[i + 1];
                numb[i + 1] = numb[i];
                numb[i] = temp;
            }
        }
        for (int i = 0; i <= 5; i++)
        {
            std::cout << numb[i] << " ";
        }

        std::cout << "\n";
        end--;
    }

    system("pause");
}

Solution

  • In you inner for loop where int i = 0; i < end; i++, you need to set the condition to be i < end - 1. This is because you are already going to be at the end of the array with i + 1 when swapping the indexes around.