The definition of
bubbleCards[]
is not shown here.
However, based on the use of variable temp,
int temp = bubbleCards[i];
it's reasonable to deduce that bubbleCards is an array of type
int
.
eselar wrote: |
---|
after i run the bubble sort, i print the elements; every element contains an assortment of characters like A0DDF288 |
Well, an integer variable cannot contain an assortment of characters. Most likely, there is something wrong with the code where you print the elements. Probably you are printing the address of the array rather than its contents.
But still, the sort does contain a serious error.
Look at this line:
for ( int i = 0; i < count; i++ )
We see a little earlier that count is 52.
Thus
i
will vary from 0 to 51 (a total of 52 elements).
Now look at the next line:
if ( bubbleCards[i] > bubbleCards[i+1] )
When
i
is 51,
bubbleCards[i]
is the last item in the array.
So what then is
bubbleCards[i+1]
?
It is the element
after the last element, the 53rd element. Or to put it another way, it is outside the array, it is some other data that should not be accessed. Attempting to use this location can give rise to unpredictable results.
The solution? Change the for-loop to use count-1, like this:
for (int i = 0; i < count-1; i++ )
A more general comment, the function would look neater if it was clear what was its input and/or output. So, rather than declaring it like this,
void BubbleSort()
, it would be better to pass the array and its size as parameters, like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
void BubbleSort(int bubbleCards[], int n)
{
int count = n;
bool moved;
do
{
moved = false;
for (int i = 0; i < count-1; i++ )
{
if ( bubbleCards[i] > bubbleCards[i+1] )
{
int temp = bubbleCards[i];
bubbleCards[i] = bubbleCards[i+1];
bubbleCards[i+1] = temp;
moved = true;
}
}
count--;
}
while (moved);
}
|