binary-search
binary-search
Binary Search is an efficient algorithm used to find the position of a target value within a
sorted array. It works by repeatedly dividing the search interval in half. If the value of
the target is less than the value in the middle of the interval, the search continues in the
lower half, or if the target is greater, the search continues in the upper half. This process
continues until the target value is found or the interval is empty.
Time Complexity
• Best Case: O(1) (if the element is at the middle of the array)
• Worst Case: O(log n) (if we need to search through the entire array)
BinarySearch(arr, target):
left = 0
right = length of arr - 1
# Example usage
arr = [1, 3, 5, 7, 9, 11, 13, 15]
target = 7
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
1. Initialize Pointers: left is set to the start of the array (index 0), and right is set
to the end of the array (index len(arr) - 1).
2. Loop Until Found: The loop continues as long as left is less than or equal to
right. The middle element is calculated using (left + right) // 2.
3. Compare the Target:
a. If arr[mid] == target, the function returns the index mid where the
target is found.
b. If arr[mid] < target, we need to look in the right half, so we move the
left pointer to mid + 1.
c. If arr[mid] > target, we need to look in the left half, so we move the
right pointer to mid - 1.
4. Target Not Found: If the target is not found, the function returns -1 indicating
the target is not in the array.
Example Walkthrough:
Let's say we have an array arr = [1, 3, 5, 7, 9, 11, 13, 15] and we want to
find the target 7.
1. Initial State:
a. left = 0, right = 7 (length of the array - 1)
b. mid = (0 + 7) // 2 = 3
c. arr[mid] = 7
Since arr[mid] is equal to the target, the function returns the index 3.
Another Example:
For the array arr = [1, 3, 5, 7, 9, 11, 13, 15] and target 10:
1. Initial State:
a. left = 0, right = 7
b. mid = (0 + 7) // 2 = 3
c. arr[mid] = 7
2. Second Step:
a. left = 4, right = 7
b. mid = (4 + 7) // 2 = 5
c. arr[mid] = 11
3. Third Step:
a. left = 4, right = 4
b. mid = (4 + 4) // 2 = 4
c. arr[mid] = 9
Now, left > right, meaning the target is not in the array, and the function returns -
1.
I hope this helps you understand the concept of binary search! Let me know if you'd like
to explore more details or examples.