Efficiently Find Elements with Binary Search
Binary search is a fundamental algorithm used for finding an element within a sorted array. It's significantly faster than a linear search for large datasets, making it a crucial tool in computer science. Your challenge is to implement this efficient search algorithm in Python.
Problem Description
You need to implement a Python function called binary_search that takes two arguments:
sorted_list: A list of numbers that is guaranteed to be sorted in ascending order.target: The number you are trying to find within thesorted_list.
The function should return the index of the target element if it exists in the sorted_list. If the target element is not present in the list, the function should return -1.
Key Requirements:
- The algorithm must be a binary search.
- The input list is guaranteed to be sorted in ascending order.
- Return the index of the target if found.
- Return -1 if the target is not found.
Expected Behavior:
Your binary_search function should efficiently locate the target element by repeatedly dividing the search interval in half.
Edge Cases to Consider:
- An empty input list.
- A list with a single element.
- The target element being the first or last element in the list.
- The target element not being present in the list.
Examples
Example 1:
Input: sorted_list = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target = 23
Output: 5
Explanation: The number 23 is found at index 5 in the sorted list.
Example 2:
Input: sorted_list = [10, 20, 30, 40, 50], target = 15
Output: -1
Explanation: The number 15 is not present in the sorted list.
Example 3:
Input: sorted_list = [], target = 10
Output: -1
Explanation: The list is empty, so the target cannot be found.
Constraints
- The
sorted_listwill contain integers. - The
targetwill be an integer. - The length of
sorted_listcan range from 0 to 10<sup>5</sup>. - The values in
sorted_listandtargetwill be within the range of standard integer types. - Your implementation should aim for a time complexity of O(log n), where n is the length of the
sorted_list.
Notes
Remember that binary search works by narrowing down the search space. You'll need to keep track of the "low" and "high" boundaries of your search interval. Consider how you'll handle the midpoint calculation and how you'll adjust the boundaries based on whether the target is greater than or less than the element at the midpoint.