Search code examples
cfor-loopshellsort

please explain shellsort code in C


This code is written in ANSI C by Ritchie..... I have used a comment in this code that my doubt. Also i have learnt shell sort from youtube and have understood how it actually works but this code is very confusing specially these loop....why have they used gap= n/2....what is gap? and what are these loop doing here.....Plz :(

void shellsort(int v[], int n) 
{
      int gap, i, j, temp;

      for(gap= n/2; gap >0; gap /=2)    // What is this gap /=2
          for(i=gap; i<n; i++)
              for(j= i-gap; j>= 0 && v[j]>v[j+gap]; j -=gap){
                   temp= v[j];
                   v[j]=v[j+gap];
                   v[j+gap]=temp;
              }
}

Solution

  • what edition of the book are you reading from? i think there are a number of programming errors in the example code all the way untill 3rd edition.

    gap refers to the int you declared above the for loop. like gap, i, j & temp are also integers. this means they hold a integer numeric value (e.g, 1,2, 12, 586 etc).

    a /= b is a division assignment so its literal meaning is a = a / b.

    you might also be wondering what v & n are?

    int v[] refers to an int array, so any value used inside the [ ] is the index of that array, e.g v[0], v[1], v[2], v[n]...

    Since v & n are declared as parameters of the shellsort function, it means that when you call the function, it will need to be passed an int array value, as well as an int value. without these values the function cannot operate properly

    if you have the C book, everything you need to know about C will be in that book :)