Skip to content

Commit 8f323f0

Browse files
[doc]: Added documentation for the binary search algorithm
1 parent 2f5bf99 commit 8f323f0

4 files changed

Lines changed: 38 additions & 2 deletions

File tree

‎src/com/sketch/Main.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.sketch;
22

3-
import com.sketch.search.*;
3+
import com.sketch.search.binarysearch.BinarySearch;
44

55
public class Main {
66
public static void main(String[] args){

src/com/sketch/search/BinarySearch.java renamed to src/com/sketch/search/binarysearch/BinarySearch.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.sketch.search;
1+
package com.sketch.search.binarysearch;
22

33
import java.util.Arrays;
44

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
![img.png](img.png)
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.
192 KB
Loading

0 commit comments

Comments
 (0)