1.
Introduction
Binary Search is a highly efficient searching algorithm for sorted arrays. It works by repeatedly
dividing the search range in half until the target is found or the search space is empty.
2. How It Works
1. Find the middle element of the current range.
2. If the middle element is the target, return its position.
3. If the target is smaller, search in the left half.
4. If the target is larger, search in the right half.
5. Repeat until found or the range is empty.
3. Pseudocode
cpp
CopyEdit
procedure binarySearch(A, target):
low = 0
high = length(A) - 1
while low <= high:
mid = (low + high) // 2
if A[mid] == target:
return mid
else if A[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
4. Example
Input: Array = [1, 3, 5, 7, 9, 11], Target = 7
Output: Index 3
5. Complexity Analysis
Time Complexity: O(log n)
Space Complexity: O(1)
Limitation: Works only on sorted data