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;
}

What is the array after the i=0 iteration completes?

  • A

    {1, 2, 5, 8, 9}

  • B

    {1, 5, 8, 2, 9}

  • C

    {2, 5, 8, 1, 9}

  • D

    {1, 2, 8, 5, 9}

    check_circle

Explanation

The minimum (1 at index 3) swaps with a[0]=5, giving {1,2,8,5,9}.

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

Related questions