Binary Search
Binary Search
Binary search is an efficient search algorithm that works on pre-sorted arrays. It repeatedly splits the search interval in half. If the target value is less than the middle element, it narrows the interval to the lower half; otherwise, it limits it to the upper half, repeating the split until the value is found or the interval is empty.
Complexity Profile
| Case | Complexity |
|---|---|
| Best Case | O(1) |
| Average Case | O(log N) |
| Worst Case | O(log N) |
| Space Complexity | O(1) |
Code Implementation
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid # Element found
elif arr[mid] < target:
left = mid + 1 # Discard left half
else:
right = mid - 1 # Discard right half
return -1 # Element not foundReal-World Applications
- Locating elements inside databases and index tables.
- Locating compiler dictionary tokens during tokenization.
- Finding numerical roots via numerical analysis approximation.
Architectural Analysis
[!tip] Deep Dive Best search algorithm for static sorted arrays. By dividing the search interval in half with each iteration, Binary Search reduces the search space exponentially, yielding O(log N) average and worst-case time complexity. It outperforms linear scans dramatically for large datasets while maintaining O(1) auxiliary space.
BFS
Breadth-First Search (BFS) is a graph traversal algorithm that explores nodes level-by-level, visiting all neighbor nodes at the current depth before moving deeper. It employs a FIFO Queue to orchestrate vertex traversal. BFS is guaranteed to discover the shortest path in unweighted graphs.
DFS
Depth-First Search (DFS) is a graph traversal algorithm that explores as deep as possible along each branch before backtracking. It relies on a LIFO Stack (or call stack recursion) to navigate vertices. DFS is essential for topological sorting, detecting cycles, and solving maze puzzles.