You have stumbled upon a group of mathematicians who are also singer-songwriters. They have written a song for each of their favorite numbers, and, as you can imagine, they have a lot of favorite numbers (like 0 or 73 or 6174).
You are curious to hear the song for your favorite number, but with so many songs to wade through, finding the right song could take a while. Fortunately, they have organized their songs in a playlist sorted by the title β which is simply the number that the song is about.
You realize that you can use a binary search algorithm to quickly find a song given the title.
Your task is to implement a binary search algorithm.
A binary search algorithm finds an item in a list by repeatedly splitting it in half, only keeping the half which contains the item we're looking for. It allows us to quickly narrow down the possible locations of our item until we find it, or until we've eliminated all possible locations.
Binary search only works when a list has been sorted.
The algorithm looks like this:
Here's an example:
Let's say we're looking for the number 23 in the following sorted list: [4, 8, 12, 16, 23, 28, 32]
.
[23, 28, 32]
.[23]
.If the element is not present in the array, return the symbol 'not-found
.
The array will be passed as a vector.
Simply type make chez
if you're using ChezScheme or make guile
if you're using GNU Guile.
Sometimes the name for the scheme binary on your system will differ from the defaults.
When this is the case, you'll need to tell make by running make chez chez=your-chez-binary
or make guile guile=your-guile-binary
.
(load "test.scm")
at the repl prompt.binary-search.scm
reloading as you go.(test)
to check your solution.If some of the test cases fail, you should see the failing input and the expected output.
The failing input is presented as a list because the tests call your solution by (apply binary-search input-list)
.
To learn more about apply
see The Scheme Programming Language -- Chapter 5
Sign up to Exercism to learn and master Scheme with 39 exercises, and real human mentoring, all for free.