Recursion · 15 / 18 Exercise Medium

Recursive binary search

Objective

Binary search splits a sorted list in half at each step, so it is another natural case for recursion: you search in one of the two halves.

Instructions

  • Read a line with integers already sorted from smallest to largest, and then an integer n with the number of searches and n more integers, one per line.
  • Define search(items, target, start, end) recursively: if start is greater than end return -1; if the middle element is the target, return its position; if it is smaller, search the right half, and if it is greater, the left one.
  • For each number show x: position with its position (starting at 0) or -1 if it is not there.
Input
1 3 5 7 9 11
3
7
4
11
Output
7: 3
4: -1
11: 5

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise