ProgrammingHardGATE CS · Product company OA

How many element shifts (executions of a[j + 1] = a[j]) does this insertion sort make?

How many element shifts (executions of a[j + 1] = a[j]) does this insertion sort make?
int a[] = {4, 3, 2, 1}, shifts = 0;
for (int i = 1; i < 4; i++) {
    int k = a[i], j = i - 1;
    while (j >= 0 && a[j] > k) { a[j + 1] = a[j]; j--; shifts++; }
    a[j + 1] = k;
}
  1. A. 6
  2. B. 4
  3. C. 10
  4. D. 3

Correct answer: A. 6

Insertion sort shifts once for each inversion (a pair out of order). A reversed array of 4 has every pair inverted: C(4, 2) = 6 (1 + 2 + 3 shifts for i = 1, 2, 3). '3' counts insertions, not shifts.

More C Programming questions

Exams that ask this topic