# Why is this bubble sort test messing up at the end?

I thought I'd do the bubble sort in a separate test window just to get it working right and it was when it was 5 ints long but I doubled the length and made shuffled the ints around and it seems to work as planned for the first few but if you see whats happening the numbers stop swapping as I'd expect them to and eventually 10 gets pushed right off of the list. Can anyone point me in the direction of whats going wrong? thanks!

int main(void)

{

int values[10] = {6, 5, 1, 8, 3, 10, 7, 4, 9, 2};

int swaps = 0;
for (int j = 0; j < 10; j++)
{
for (int i = 0; i < 10; i++)
{
swaps = 0;
if (values[i] > values[i + 1])
{
printf("Before swap -->  ");
for(int l = 0; l < 10; l++)
{
printf("%d ", values[l]);
}
printf("\n");

int num1 = values[i];
values[i] = values[i + 1];
values[i + 1] = num1;

printf("After swap  -->  ");
for(int l = 0; l < 10; l++)
{
printf("%d ", values[l]);
}
printf("\n\n");

swaps++;
}

}
}
for(int l = 0; l < 10; l++)
{
printf("%d ", values[l]);
}
printf("\n%i\n", swaps);


}

Here's part of the output that I print to check whats going on. As you can see in the 3rd iteration weirdness starts:

Before swap --> 6 5 1 8 3 10 7 4 9 2 After swap --> 5 6 1 8 3 10 7 4 9 2

Before swap --> 5 6 1 8 3 10 7 4 9 2 After swap --> 5 1 6 8 3 10 7 4 9 2

Before swap --> 5 1 6 8 3 10 7 4 9 2 After swap --> 5 1 6 3 8 10 7 4 9 2

Before swap --> 5 1 6 3 8 10 7 4 9 2 After swap --> 5 1 6 3 8 7 10 4 9 2

Before swap --> 5 1 6 3 8 7 10 4 9 2 After swap --> 5 1 6 3 8 7 4 10 9 2

Before swap --> 5 1 6 3 8 7 4 10 9 2 After swap --> 5 1 6 3 8 7 4 9 10 2

Before swap --> 5 1 6 3 8 7 4 9 10 2 After swap --> 5 1 6 3 8 7 4 9 2 10

Before swap --> 5 1 6 3 8 7 4 9 2 10 After swap --> 5 1 6 3 8 7 4 9 2 0

This is a simple oversight error. Your code is actually working, but makes one small mistake. Look at the following two lines of code:

for (int i = 0; i < 10; i++)
...
values[i] = values[i + 1];


What happens when i=9? Is values[i+1] valid? i+1 = 10, but the range for the array is 0 to 9. This is ejecting the 10 from the array and bringing a 0 in.

I'll leave it to you to figure out the simple fix. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

• Ok great that totally helped. thanks! Apr 5 '16 at 20:27