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;
}- A. 6
- B. 4
- C. 10
- 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
- How many passes of the outer loop run? c int a[] = {2, 3, 4, 5, 1}, passes = 0; for (int sw = 1; sw; ) { sw = 0; passes++; for (int j = 0…
- What is printed? c int m[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { int t =…
- What is printed? c int x = 5; x = x << 2 >> 1; printf("%d", x);
- What is printed? c int x = 9, y = 0; if (x = y == 0) printf("A%d", x); else printf("B%d", x);
- What is printed? c int f(int a, int b) { return a 10 + b; } int main(void) { printf("%d", f((1, 2), 3)); }
- What is printed? c int x = 0; if (x == 1); x += 5; printf("%d", x);