|
| 1 | +# Binary Search Algorithm |
| 2 | + |
| 3 | +**Binary Search** is a searching algorithm that operates on a sorted or monotonic search space, repeatedly dividing it into halves to |
| 4 | +find a target value or optimal answer in logarithmic time **O(log N**. |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | +The Binary Search algorithm can only be applied to data-structures that: |
| 9 | +- are sorted, |
| 10 | +- and access to any element of the data-structure takes constant time **O(1)**. |
| 11 | + |
| 12 | +How does it work: |
| 13 | +- Divide the data-structure into two halves by finding the middle index '`mid`' |
| 14 | +- Compare the value at `mid` with the `key` |
| 15 | +- If the `key` is equals to the value at `mid`, then terminate the process |
| 16 | +- If the `key` is not found at the middle, choose which half hald will be used as the next search space. |
| 17 | + - If the `key` is smaller than the middle, then the `left` side is used for the next search. |
| 18 | + - If the `key` is larger than the middle, then the `right` side is used for the next search. |
| 19 | +- This process is continues until the `key` is found or the total search space is exhausted. |
| 20 | + |
| 21 | +## Complexity Analysis |
| 22 | +- **Time Complexity** |
| 23 | + - Best Case: O(1) |
| 24 | + - Average Case: O(log N) |
| 25 | + - Worst Case: O(log N) |
| 26 | +- **Auxiliary Space**: |
| 27 | + - Normal Implementation: O(1) |
| 28 | + - Recursive Implementation: O(log N) |
| 29 | + |
| 30 | +## Applications |
| 31 | +- Searching in sorted arrays |
| 32 | +- Finding first/last occurrence or closest match in a sorted array |
| 33 | +- Database indexing — Used in B-trees and similar structures for fast data lookup. |
| 34 | +- File systems & libraries — Fast search through sorted directories or symbol tables. |
| 35 | +- Machine learning tuning — Efficient hyperparameter search (e.g., learning rate, thresholds). |
| 36 | +- Network routing & IP lookup — Efficiently find routing entries in tables sorted by address ranges. |
0 commit comments