# Thread: a little help with bubble sort

1. ## a little help with bubble sort

Hi all, i did a search on google with bubble sort to read up on the algorithm and it sounds easy enough but i just have a question on it regarding the swapping of numbers in the arrays..

Code:
```for ( j = 1; j <= 4; j++ )
for( i = 0; i <= 3; i++ )

if ( a[ i ] > a[ i + 1 ] ) {
hold = a[ i ];
a[ i ] = a[ i + 1 ];
a[ i + 1 ] = hold;
}```
if i have say 5 numbers 7, 19, 10, 5, 89
after the first pass 7 gets compared to 19 and since its false it stays.
so then it does a second pass? and compare 19 with 10 which is true.. so
hold = 19;
19 = 10;
10=hold;

so at this point in time do the array values change? so 19 and 10 get swapped around? then a 3rd pass begins comparing 19 and 5?

2. first pass:
(7 19) 10 5 89 -- compare those
7 (19 10) 5 89 -- compare those (swap)
7 10 (19 5) 89 -- compare those (swap)
7 10 5 (19 89) -- compare those

second pass:
(7 10) 5 19 89 -- compare those
7 (10 5) 19 89 -- compare those (swap)
7 5 (10 19) 89 -- compare those
7 5 10 (19 89) -- compare those

etc..

3. I think ive got the idea now, and also how would i trace this program? like show each step of the way until it ends? How can i change the code below to output a trace.

Code:
```#include <stdio.h>
#define SIZE 10

int main()
{
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
int i, pass, hold;

printf( "Data items in original order\n" );

for ( i = 0; i <= SIZE - 1; i++ )
printf( "%4d", a[ i ] );

for ( pass = 1; pass <= SIZE - 1; pass++ )

for( i = 0; i <= SIZE - 2; i++ )
printf( "%d %d ", a[ i ], hold );
if ( a[ i ] > a[ i + 1 ] ) {
hold = a[ i ];
a[ i ] = a[ i + 1 ];
a[ i + 1 ] = hold;
}

printf( "\nData items in ascending order\n" );

for ( i = 0; i <= SIZE - 1; i++ )
printf( "%4d", a[ i ] );

printf( "\n" );

return 0;
}```