ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    int a[] = {3, 1, 2}, swaps = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 2 - i; j++)
            if (a[j] > a[j + 1]) {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
                swaps++;
            }
    printf("%d", swaps);
}
  1. A. 3
  2. B. 1
  3. C. 4
  4. D. 2

Correct answer: D. 2

Each swap removes exactly one inversion, and {3, 1, 2} has two inversions, (3,1) and (3,2). So the bubble sort makes two swaps.

More C Programming questions

Exams that ask this topic