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

  • A

    {5, 2, 8, 1, 9}

  • B

    {1, 2, 5, 8, 9}

  • C

    {2, 5, 1, 8, 9}

  • D

    {2, 5, 8, 1, 9}

    check_circle

Explanation

After inserting a[1]=2 into the sorted prefix, only 2 and 5 swap.

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

Related questions