roncook roncook - 2 months ago 14
C Question

Why does the output of my bubble sort program change each time I run it?

Here is my code:

#include<stdio.h>
#include<cs50.h>

int main(void)
{
int array[8] = {2, 5, 3, 1, 4, 6, 9, 7};

for (int j = 0; j < 8; j++)
{
for (int i = 0; i < 8 ; i++)
{
if (array[i] > array[i + 1])
{
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}

for (int i = 0; i < 8; i++)
printf("%i", array[i]);

printf("\n");
}


And here is a screenshot of my terminal window: http://i.imgur.com/Q1yCsgR.jpg

As you can see, I made no changes, just kept running it until it finally worked. What's more is that when i tried adding a variable n in main that stored the sizeof the array, and replaced the '8' in the for loops with n, the output to the terminal window just went absolutely crazy and refused to tend towards the correct answer each time I ran it.

usr usr
Answer
        if (array[i] > array[i + 1])

In the above if statement, when i is 7, you are accessing out of bounds and that leads to undefined behaviour. You can fix it by changing the for loop condition to:

    for (int i = 0; i < 7 ; i++)
Comments