0
void sort(int values[], int n)
{
    int sorted;
    do
    {
        sorted = 0;
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < i; j++)
            {
                if ((values[j]) > (values[j+1]))
                {
                    int swap = values[j];
                    values[j] = values[j+1];
                    values[j+1] = swap;
                    sorted++;
                }
            }
            n = n - 1;
        }
        // Prints ints to screen for debugging
        for(int a = 0; a < n; a++)
        {
            printf("%i\n", values[a]);
        }
    }
    while (sorted != 0);
    return;
}

When the values are printed , they do not appear to have been sorted. Is this because my printf function is in the wrong place and they are printing to screen before the sort has occurred, or are no swaps taking place and my bubble sort isn't working?

1 Answer 1

1

First of all the do{} while loop and the sorted variable are redundant, you should remove them.

Then, the for loops aren't properly initialized. What they should do is

for i decreasing from n to 1
    for j increasing from 0 to i
        if...

Well that's just one way of phrasing it, there are others too. What your code does is

for i increasing from 0 to n
     for j increasing from 0 to i
          if...

As you may know, with bubble sorting, after you go through all numbers comparing them in pairs the last number is sure to be in the right position. I'm guessing this is what you tried doing in your code, but it doesn't work because first time going through the numbers comparing them it only compares the first 2 numbers, then the first 2 again and the second with the third and so on. When this happens the numbers that are in the back of the list and should be at the front do not go through enough comparisons to be put in the right position. First time the computer goes through the list it should compare all numbers, then all numbers except for the last one and so on.

1
  • Why would I get rid of the counter variable sorted. I thought I need it in order to keep track of whether or not a swap has been made after a pass through? Commented Sep 8, 2016 at 19:59

You must log in to answer this question.

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