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

  • A

    {1, 2, 5, 8, 9}

    check_circle
  • B

    {1, 2, 5, 8, 9}

  • C

    {1, 5, 2, 8, 9}

  • D

    {2, 5, 8, 1, 9}

Explanation

a[3]=1 is shifted to the front; the array becomes sorted: {1,2,5,8,9}.

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

Related questions