educative.io

Educative

Is it necessary to account for short-circuit evaluation of the "and" operator

The challenge question asks how many instructions are needed for the implementation of the insertion sort algorithm shown below. It asks what is the best case scenario for a length 5 array when the array is already in sorted order? Correct answer according to the official solution is 32. However, it is not clear whether this should take into account short-circuit evaluation of the “and” operator.

  for (int i = 0; i < input.length; i++) {
      int key = input[i];
      j = i - 1;
      while (j >= 0 && input[j] > key) {
          if (input[j] > key) {
              int tmp = input[j];
              input[j] = key;
              input[j + 1] = tmp;
              j--;
           }
      }
  }

I think since the author has mentioned that he is assuming that we don’t short circuit, the instruction count will be 32. But this assumption is not necessarily true, as in the case of i==0. In case it short circuits, the instruction count of the inner while loop will be 9 instead of 10, and the total instruction count will be 31.