ProgrammingVery hardProduct company OA · GATE CS
How many passes of the outer loop run?
How many passes of the outer loop run?
int a[] = {2, 3, 4, 5, 1}, passes = 0;
for (int sw = 1; sw; ) {
sw = 0;
passes++;
for (int j = 0; j < 4; j++)
if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; sw = 1; }
}- A. 4
- B. 2
- C. 5
- D. 1
Correct answer: C. 5
A small value at the end (a 'turtle') moves left only one place per bubble-sort pass, so the 1 needs 4 passes with swaps to reach the front, and a fifth pass with no swaps is needed to detect that the array is sorted. A large value at the start would have needed just 1 swapping pass.
More C Programming questions
- 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);
- What is printed? c int inc(int x) { return x + 1; } int dec(int x) { return x - 1; } int (pick(int c))(int) { return c ? inc : dec; } int…