Binary Search
In this challenge, you'll implement a binary search function!
Imagine you have a large number of sorted candy jars lined up in a row, and you're looking for one specific jar with your favorite candy in it. You could check each jar one by one, but wouldn't it be faster if you skipped to a middle jar and decided whether to look on the right or left next? This is the idea behind binary search!
The goal of binary search is to efficiently find a target number in a sorted list of numbers.
Here's how it works:
- Pick the middle element of the list.
- If the middle element is the target, return its position.
- If the target is less than the middle element, search the left half of the list.
- If the target is more than the middle element, search the right half of the list.
- Repeat the process on the half list until you find the target or the list becomes empty.
The key is that the list must be sorted first, so make sure your list is always sorted!
Your task is to implement binary_search function which takes a sorted list of integers and a target integer.
The function should return the index of the target in the list, or -1 if the target is not found.
Example:
binary_search([1, 3, 5, 7, 9, 11], 7) # Returns: 3 binary_search([10, 20, 30, 40, 50], 25) # Returns: -1 binary_search([2, 4, 6, 8, 10, 12, 14], 10) # Returns: 4
Have fun coding and happy searching!
Inputs
Arg 1:
[1,3,5,7,9,11]Arg 2:
7Expected Output
3Actual Output