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
nwith the number of searches andnmore integers, one per line. - Define
search(items, target, start, end)recursively: ifstartis greater thanendreturn-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: positionwith its position (starting at 0) or-1if it is not there.
1 3 5 7 9 11
3
7
4
11
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