質問

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:

  • selection is my variable for choosing what's getting done in my program. In this particular instance the bubble sort selection is 16.

  • arraySize is the user specified size of the array.

  • bubbleCount is just an arbitrary name for the typical for loop arrays use.

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?

役に立ちましたか?

解決

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] );
            }
        }
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top