user3068686
user3068686

Reputation:

Getting Bubble sort to work in C++

else if (selection == 16)
{
    int bubbleCount = 0;
    for(bubbleCount = 0; bubbleCount < arraySize; bubbleCount++)
    {
        if (theArray[bubbleCount] > theArray[bubbleCount+1])
        {
            swap(theArray[bubbleCount], theArray[bubbleCount+1]);
        }
    }
}

For clarification of what's going on here:

I thought my logic was fine. What should happen is the array starts at my count and compares it to the adjacent element in the array. If it's larger, they swap. The for loop should execute for arraySize iterations. When I tested this with an array of randomly generated numbers, it failed to fully sort. Where did I mess up?

Upvotes: 0

Views: 218

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

Change the code snippet the following way

// enum { BubbleSort = 16, /*...*/ }

else if ( selection == BubbleSort )
{
    for( int last = arraySize; last > 1 ; --last )
    {
        for ( int first = 1; first < last; ++first )
        {
            if ( theArray[first] < theArray[first - 1] )
            {
                swap( theArray[first], theArray[first - 1] );
            }
        }
    }
}

Upvotes: 1

Related Questions