Analysis of binary search
Binary Search
Binary search is an efficient algorithm for finding an item in a sorted list or array. It works by repeatedly dividing the search interval in half. It follows dictionary opening order
How It Works
- Compare the target value to the middle element of the array
- If the target equals the middle element, return its position
- If the target is less than the middle element, search the left half
- If the target is greater than the middle element, search the right half
- Repeat until the element is found or the interval is empty
Time Complexity
O(log n) - Much faster than linear search (O(n)) for large datasets
Space Complexity
O(1) for iterative implementation
O(log n) for recursive implementation (due to call stack)
Step-by-Step Execution with Example
Searching for 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]:
First iteration:
Left=0, Right=9
Mid=(0+9)//2=4
data[4]=16 < 23 → search right (Left=5) middle element as per position 16 but we are searching for element 23
Second iteration:
Left=5, Right=9
Mid=(5+9)//2=7
data[7]=56 > 23 → search left (Right=6)
56 is greater than 23 so, our search goes to left
Third iteration:
Left=5, Right=6
Mid=(5+6)//2=5
data[5]=23 == target → return 5
The algorithm found the required number in 3 steps (O(log n) time complexity) instead of potentially 10 in a linear search.
Key Points:
- Requires sorted data
- All elements must be unique (or you need additional logic for duplicates)
- Very efficient with O(log n) time complexity
- Space complexity is O(1) as it uses constant extra space
Comments
Post a Comment