ProgrammingHardProduct company OA · GATE CS

How many swaps does this selection sort perform?

How many swaps does this selection sort perform?
int a[] = {3, 1, 2, 5, 4}, sw = 0;
for (int i = 0; i < 4; i++) {
    int m = i;
    for (int j = i + 1; j < 5; j++) if (a[j] < a[m]) m = j;
    if (m != i) { int t = a[i]; a[i] = a[m]; a[m] = t; sw++; }
}
  1. A. 4
  2. B. 5
  3. C. 3
  4. D. 2

Correct answer: C. 3

Pass 0 swaps 3 and 1 → 1 3 2 5 4. Pass 1 swaps 3 and 2 → 1 2 3 5 4. Pass 2 finds 3 already in place (no swap). Pass 3 swaps 5 and 4. Three swaps; the m != i test is what skips pass 2.

More C Programming questions

Exams that ask this topic