Day 25: Binary Search and Its Variations
Binary Search and Its Variations #
Welcome to Day 25 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore Binary Search, a fundamental search algorithm, and its various variations. Binary Search is known for its efficiency in searching sorted arrays and forms the basis for many other algorithms.
Introduction to Binary Search #
Binary Search is a divide and conquer algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until the target value is found.
Basic Binary Search #
Here’s an implementation of the basic binary search algorithm:
1def binary_search(arr, target):
2 left, right = 0, len(arr) - 1
3
4 while left <= right:
5 mid = (left + right) // 2
6 if arr[mid] == target:
7 return mid
8 elif arr[mid] < target:
9 left = mid + 1
10 else:
11 right = mid - 1
12
13 return -1 # Target not found
14
15# Example usage
16arr = [1, 3, 5, 7, 9, 11, …
Continue Reading
Sign up or log in to access the full lesson and all 60 days of algorithm content.