1
for(i = 1; i < len; i++){
    for(j = i - 1; j >= 0; --j){
        if(data[j] > data[1 + j]){
            swap(j, j + 1);
        } else {
            break;
        }
    }
}

swap method does swapping elements. Why it should be --j instead of j-- ? what is the difference ? what is the advantage of putting j-- ?

mch
  • 9,424
  • 2
  • 28
  • 42

2 Answers2

2

In this context both work.

In C++ there are good reasons to use ++i. Since you're coding in C choose one and stick with it.

jimifiki
  • 5,377
  • 2
  • 34
  • 60
1

For primite types there is no performance difference between postfix and prefix increment/decrement.

By the way there is more efficient insertion sort algo implementation, only 1 assignment in inner loop (swap performs 3).

int i, key, j;
for (i = 1; i < n; i++)
{
   key = arr[i];
   j = i-1;
   for (j = i-1; j >= 0 && arr[j] > key; --j) {
       arr[j+1] = arr[j];
   }
   arr[j+1] = key;
}
oybek
  • 630
  • 4
  • 14