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=2 iteration completes?

  • A

    {1, 2, 5, 9, 8}

  • B

    {1, 2, 8, 5, 9}

  • C

    {1, 2, 9, 8, 5}

  • D

    {1, 2, 5, 8, 9}

    check_circle

Explanation

From {1,2,8,5,9}, the smallest in suffix is 5; swap with a[2]=8 to get {1,2,5,8,9}.

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

Related questions