Sorting

AP Computer Science A· difficulty 3/5

int[] a = {5, 2, 8, 1, 9};
for (int i = 1; i < a.length; i++) {
  int v = a[i];
  int j = i - 1;
  while (j >= 0 && a[j] > v) {
    a[j+1] = a[j];
    j--;
  }
  a[j+1] = v;
}

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

  • A

    {2, 8, 5, 1, 9}

  • B

    {2, 5, 8, 1, 9}

    check_circle
  • C

    {2, 5, 1, 8, 9}

  • D

    {1, 2, 5, 8, 9}

Explanation

a[2]=8 is already greater than 5, so no shifts occur; array stays {2,5,8,1,9}.

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

Related questions