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; }
}
  1. A. 4
  2. B. 2
  3. C. 5
  4. 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

Exams that ask this topic