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++; }
}- A. 4
- B. 5
- C. 3
- 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
- How many element shifts (executions of a[j + 1] = a[j]) does this insertion sort make? c int a[] = {4, 3, 2, 1}, shifts = 0; for (int i =…
- 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)); }