Binary search
Inputs
values is a list of 0 to 14 different whole numbers in increasing order, each from 0 to 60. target is a whole number from 0 to 60.
Your tasks
- Set
lowto 0 andhighto the last position. - Use a
whileloop that runs whilelow <= high. Look at the middle positionmid(halfway betweenlowandhigh, rounded down). - If
values[mid]is the target, returnmid. If it is too small, movelowtomid + 1. If it is too big, movehightomid - 1. - Complete
binarySearchso it returns the position oftarget, or -1. Return it, do not print it.
Example
With values = [2, 5, 9, 14, 21, 30] and target = 14, binarySearch returns 3.
Rules
- Do not look at every number. Halve the search each time.
Test data
TEST DATA 1: values is [2, 5, 9, 14, 21, 30], target is 14
TEST DATA 2: values is [1, 3], target is 2
Practice focus
Prefix sums, counting, binary search, best stretch and sorting, all written as plain loops. This is where loops turn into named algorithms. You have already written the loops.