1

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?

2
  • 1
    Please give your full code Commented Jul 7, 2015 at 0:15
  • 1
    You need to end the inner loop one element earlier, since you refer to values[j+1] inside it. Your last iteration accesses one element past the end of the array right now. Commented Jul 7, 2015 at 0:17

1 Answer 1

6

Your swap function is fine... the problem is that you access outside the array bounds in the inner for loop. In that loop, you have j ranging from 0 to the last array index, so values[j] will be at most the last element of the array... however, you're working with two elements at a time, values[j] and values[j+1]... and on the last iteration, values[j+1] is out of bounds.

The solution is just to stop your inner loop one iteration earlier, ie.:

    for(j = 0; j < (sizeof(values)/sizeof(values[0]) - 1); j++){
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, for some reason I tried for(j = 0; j < (sizeof(values)/sizeof(values[0]) - sizeof(values[0]); j++){ I'm not very familiar with C quite yet, so getting the hang of it all. thank you so much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.