Binary Search is an extraordinarily common interview algorithm and application question. The goal is to find the index of a value that you pass in compared to a sorted array of strings or integers. You can read more here.
Let's take a look at some code:
values = random.sample(list(range(1,10000)), 1000)
values.sort() # We now have a sorted list of 1000 unique values between 1 and 10,000
binary_search(537, values) # this returns the index of 537 in values if it exists and -1 if it doesn't exist
Here's the basic premise of the algorithm:
- Say you're searching for a value
number_to_find
in a search set ofsorted_values
- Find the middle value in
sorted_values
we'll callmiddle_value
- If
number_to_find
is equal tomiddle_value
then your target is found - If
number_to_find
is less thanmiddle_value
, split yoursorted_values
in half and repeat the algorithm on your new subset (the half ofsorted_values
beforemiddle_value
) - If
number_to_find
is greater thanmiddle_value
, repeat step but with the half ofsorted_values
valuesafter
middle_value` - Repeat until you find
number_to_find
or return-1
if it doesn't exist
This is a difficult algorithm. Spend a LOT of time pseudocoding before even starting to code