Sairat - 1 year ago 55
C Question

# Bubble Sort in C wrong code! [Deitel C 6th Ed]

``````int main(void)
{
int a[5] = {36,24,10,6,12};
int pass;
int i;
int hold;

/* bubble sort */
/* loop to control number of passes */

for(pass=1; pass<5; pass++){
/* loop to control number of comparisons per pass */
for(i=0; i<5; i++){
if(a[i] > a[i+1]){
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}

return 0;
}
``````

In this bubble sort program the if statement comparing adjacent element’s value.
If counter I becomes 4 then if statement would be if a[4] > a[4+1] so my question is there’s no a[5] element in the array so how program is comparing and doing work?

I don’t understood for(pass=1; pass<5; pass++) loop. What this loop work for? And why the loop starts from 1 and continues 4 times instead of 5.

Anybody please demonstrate how this bubble sort program is working? Cheers!

Well, everyone answered this in the comments, but noone took the time to write an actual answer, so I'd take the role.

1st thing first, the code you pasted has a Bug in it:
while the array `int a[5]` has 5 members [0..4],
when executing the inner loop `for(i=0; i<5; i++)` given `i=4`,
`a[i+1]` is accessing `a[5]` which is out of bounds of the array and it's value is probably unexpected.
Worth Noting: because the example values `int a[5] = {36,24,10,6,12};` are very small, there is a high chance (36 / 2^32) that the code will work anyway because the `a[5]` will have the maximum value, and won't be overridden or moved.

but if you'd try changing the values to, lets say, `int a[5] = {36,0xFFFFFFFF,10,6,12};`, the program will surely fail miserably!

with each iteration (pass), the maximum value is bubbled to it's place, and therefore will be in place...
for 5 numbers, after placing 4 in their place, the last one is given implicitly.
and that's why there is no need for the 5th iteration.

also, it is common in the 2nd to last iterations to exclude the last elements from the inner loop, as they are known to be in place.

``````int main(void)
{
int a[5] = {36,24,10,6,12};
int pass;
int i;
int hold;

/* bubble sort */
/* loop to control number of passes */

for(pass=4; pass > 0; pass--){ /* pass counts down 4 iterations */
/* loop to control number of comparisons per pass */
/* 0..4, then 0..3 > 0..2, and lastly 0..1 */
for(i=0; i<pass; i++){
if(a[i] > a[i+1]){
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}
return 0;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download