Binary search
If I give you a sorted vector of integers, you can search through it quickly using binary search to know if it contains a given number n
. Is n
right in the middle? If yes, you're done. If not, then you either have to search the left half or the right half. Since the numbers are sorted, you can check if n
is greater than or less than the middle number. You can then recurse down into the appropriate half. Your task is to write this function.
(binary-search 3 [1 2 3]) ;=> true
(binary-search 4 [1 2 5]) ;=> false
(binary-search 10 [1 2 4 5 9 10 11 12]) ;=> true
You can assume you're passed a sorted vector.
Thanks to this site for the challenge idea where it is considered Hard level in Python.
Email submissions to eric@purelyfunctional.tv before August 29, 2020. You can discuss the submissions in the comments below.