I have a bubble sort that takes 10 numbers. Before I modularized it it worked fine, but somehow when I created my modules this strange error occurs: The highest value always gets placed into values[1] as 0. For example, if the user types in "1,2,3,4,5,6,7,8,9,10" the program would output "1,0,2,3,4,5,6,7,8,9." I've been at this for hours with no success and I can't find any logic or syntax errors. Please help! Here's the code:
Inner loop termination condition should be inner < SIZE - outer - 1. Outer loop termination is OK IMO.
The reason you are getting zero is because 10 gets swapped with the undefined value at values [SIZE], zero in your case. This zero is brought to the beginning of the array by the bubble sort. Give it one more outer loop iteration and you will see that it goes to position 0.
Wow, thanks a ton, that fixed it. Just to help me understand it:
1.) Why was the inner loop only causing a fencepost error when I divided the program into modules? When I wrote the program all in int main() it worked fine.
and 2.) Why was the undefined value (0) being stored in values[1] instead of values[0]?
@OP
In such array traversals, you have to be careful about boundary conditions. The values array has a size SIZE.
When your outer index is zero, the inner index loops till SIZE - 1.
Hence inner + 1 = SIZE. Within the loop, you are trying to access values[inner + 1]. values[SIZE] is undefined.
Hence what you were seeing was undefined behaviour.