Sorting

AP Computer Science A· difficulty 3/5

int[] a = {5, 2, 8, 1, 9};
for (int i = 0; i < a.length - 1; i++) {
  int min = i;
  for (int j = i + 1; j < a.length; j++) {
    if (a[j] < a[min]) min = j;
  }
  int t = a[i]; a[i] = a[min]; a[min] = t;
}

How many swaps does the outer loop execute?

  • A

    5

  • B

    4

    check_circle
  • C

    3

  • D

    2

Explanation

Selection sort swaps once per outer iteration; with n=5, that's n-1 = 4 swaps.

Want 10 more like this — adaptive to your weak spots?

Related questions