A binary search algorithm is a search algorithm used to find the position of a specific value (called "target") within a sorted array of elements. The algorithm works by repeatedly dividing in half the portion of the array being searched until the target value is found or the portion being searched is empty.
The basic steps of a binary search algorithm are:
1. If the array is empty, return "not found".
2. Pick the middle element of the array.
3. If the middle element is equal to the target value, return its position in the array.
4. If the middle element is greater than the target value, repeat the search on the left half of the array.
5. If the middle element is less than the target value, repeat the search on the right half of the array.
Here’s an example implementation of a binary search algorithm in Python:
def binary_search(array, target):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
if array[mid] == target:
return mid
elif array[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
In this implementation, the ‘array‘ parameter is the sorted array being searched, and the ‘target‘ parameter is the value being searched for. The ‘low‘ variable keeps track of the index of the first element being searched, and the ‘high‘ variable keeps track of the index of the last element being searched. The algorithm starts by setting ‘low‘ to 0 and ‘high‘ to the index of the last element, and then enters a loop that continues until the ‘low‘ index is greater than the ‘high‘ index (meaning the portion of the array being searched is empty).
Inside the loop, the algorithm calculates the index of the middle element using integer division. If the middle element is equal to the target value, the algorithm returns its index. If the middle element is less than the target value, the algorithm updates ‘low‘ to be ‘mid + 1‘, effectively narrowing the search to the right half of the array. If the middle element is greater than the target value, the algorithm updates ‘high‘ to be ‘mid - 1‘, effectively narrowing the search to the left half of the array.
If the target value is not found after the loop, the algorithm returns -1 to indicate that the value was not found in the array.
Overall, a binary search algorithm is an efficient way to search for a target value within a sorted array, because it eliminates half of the remaining values at each step of the search. The time complexity of a binary search algorithm is O(log n), where n is the number of elements in the array.