Recursive Searching and Sorting (Binary Search, Merge Sort)

AP Computer Science A· difficulty 3/5

int[] left = {2, 5, 8};
int[] right = {1, 3, 7};
int[] out = new int[6];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
  if (left[i] <= right[j]) out[k++] = left[i++];
  else out[k++] = right[j++];
}
while (i < left.length) out[k++] = left[i++];
while (j < right.length) out[k++] = right[j++];

What is out after merging?

  • A

    {1, 2, 3, 5, 7, 8}

    check_circle
  • B

    {1, 3, 7, 2, 5, 8}

  • C

    {8, 7, 5, 3, 2, 1}

  • D

    {2, 5, 8, 1, 3, 7}

Explanation

The merge interleaves to produce a fully sorted array.

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

Related questions