0

I'm trying to implement the bubble sort algorithm in , but it's not working! Pretty sure it's because of failure to swap. Been working on it for a while, with no success. Here's the relevant code:

/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    //iterates through the entire array. Stops 1 short of full array so that i+1 doesn't go past end (didn't work when it was n-1 either)
    for (int i = 0; i < (n-2); i++) {
        // if a value is greater than value after it...
        if (values[i] > values[i+1]) {
            // swap the values location ('&' is location)
            swap(&values[i], &values[i+1]);

            // testing to see if works
            printf("value [%d] = %d\n", i, values[i]);
        }
    }

    return;
}

// the '*' shows that dealing with location of a and b, not making a copy of them
void swap(int* a, int* b) {
    // placeholder value
    int temp;
    temp = *a;
    *a = *b;  
    *b = temp;
}

Thanks in advance to anyone who takes a look!

1

The problem here is that the code only makes one pass through the list. It will bubble the largest element to the end of the list, but then stops. It needs to come back to the beginning and repeat the process to sort the next largest item up, and again for the 3rd largest, 4th, 5th, etc.

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

| improve this answer | |
  • yes, this is your main problem, idk how i missed that – user3781458 May 22 '16 at 21:48
0
for (int i = 0; i < (n-2); i++) 

you should replace n-2 by n-1, or else, you're missing the last element

| improve this answer | |
  • Didn't seem to help the main error, but thanks. Wasn't sure if i+1 would be affected if 'i' stopped at n-1 – David M May 22 '16 at 21:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .