I am working on a small bubble sort program in C. I am using a swap function and pointers to accomplish my task, my program runs fine. However, I have an issue. My program returns a 0 (which isn't in the array) and doesn't return a 9. I am very confused.
My array is: int values[] = {7, 3, 9, 4, 6, 1, 2, 8, 5};
And my two functions are:
void sort(){
int i;
int j;
for(i = 0; i < (sizeof(values)/sizeof(values[0])); i++)
{
for(j = 0; j < (sizeof(values)/sizeof(values[0])); j++)
{
if(values[j] > values[j + 1]){
swap(&values[j], &values[j + 1]);
}
}
}
}// end sort
void swap(int* i, int* j){
int x = *i;
*i = *j;
*j = x;
}//end swap
And finally, after running my program I get:
Before:
7 3 9 4 6 1 2 8 5
After:
0 1 2 3 4 5 6 7 8
What is the solution?
values[j+1]inside it. Your last iteration accesses one element past the end of the array right now.