Search code examples
calgorithmfor-loopbubble-sort

Trying to understand bubblesort function


I am fairly new to C and programming in general, and I have a question about looping in the following bubble sort function:

    void sort(int values[], int n);
    {
        int c, d, t;

        for (c = 0; c < (n - 1); c++)
        {
            for (d = 0; d < c - n - 1; d++)
            {
                if (values[d] > values[d + 1])
                {
                    t = values[d];
                    values[d] = values[d + 1];
                    values[d + 1] = t;
                }
            }
        }
    }

The part that I'm specifically trying to understand is the second for loop:

    for (d = 0; d < c - n - 1; d++)

I understand that the function is iterating through the array each time, comparing side-by-side values up until the last sorted element and bubbling the biggest element to the end of the array; however, I cannot seem to wrap my head around the meaning of:

    while d < c - n - 1;

and how it translates. When I play this out in my mind I'm imagining that on the first time looping, d < c - n - 1 equates to 0 < 0 - 10 - 1. It seems to me that since c is always going to be less than n - 1, subtracting n - 1 from c will always result in a value less than 0, and d is never less than 0 so should never execute. I know that I'm just looking at this wrong and will probably have a 'duh' moment when the answer is presented, but this is bothering me.

If I put the first for loop into words, it says: while c is less than the length of the array, execute the contents of this loop then increment c. Can someone put the second for loop into words in a similar way, explaining the meaning of d < c - n - 1?


Solution

  • Try this code instead.

    #include<stdio.h>
    
    void sort(int values[], int n)
    {
    int c,d,t=n;
    //if we have n elements then outer loop must iterate for n times.
    for(c=0;c<n;c++)
    {
        /*after every complete iteration we get a
        sorted element in last position, next iteration
         will be one less, so we assigned value of n into t
         and we will decrease it by 1 after every internal complete iteration.
         */
         for(d=0;d<t-1;d++)
            {
              if(values[d]>values[d+1])
                {
                   int temp;
                   temp = values[d+1];
                   values[d+1] = values[d];
                   values[d] = temp;
                }
            }
        //decrease the test cases in next iteration,
        //we already have last element sorted.
        t--;
      }
    }
    int main()
    {
      int i;
      int values[]={24,12,2,4,6};
      sort(values, 5);
    
       for(i=0; i<5; i++)
         {
            printf("%d\n",values[i]);
         }
    
    return 0;
    }
    

    Make Changes according to your need.