Binary Search
What is Searching?
Searching is the process of finding a particular item (called key) from a collection of items (like an array, list, or database).
If the item is found, we usually return its position (index).
If the item is not found, we indicate that the search was unsuccessful.
Searching is very important in real-world applications like:
Finding a name in a contact list 📞
Searching a product on an online store 🛒
Looking up a word in a dictionary 📖
🌟 What are Search Algorithms?
Search Algorithms are special methods or procedures to locate the target value within a dataset.
Common search algorithms include:
Linear Search
Binary Search
Hashing-based Search
Search Trees (like Binary Search Trees)
🌟 What is Binary Search?
Binary Search is an efficient search algorithm that finds the position of a target value in a sorted array.
-
It divides the search space into two halves each time.
-
It eliminates half of the remaining elements at every step.
-
Works only when the array is sorted in ascending or descending order.
🌟 Idea Behind Binary Search
-
Start by comparing the middle element of the array with the target.
-
If the middle element is equal to the target → found ✅
-
If the target is smaller than the middle element → search left half.
-
If the target is greater than the middle element → search right half.
-
Repeat the process on the chosen half until you find the element or the range becomes empty.
📋 Binary Search Algorithm (Iterative)
-
Set two pointers:
low = 0
(start index)
high = n-1
(end index) -
While
low <= high
:-
Calculate
mid = (low + high) / 2
-
If
arr[mid] == key
, returnmid
(element found). -
Else if
key < arr[mid]
, sethigh = mid - 1
(move to left half). -
Else set
low = mid + 1
(move to right half).
-
-
If
low > high
, element not found. Return -1.
📋 Binary Search Algorithm (Recursive)
-
If
low > high
, return -1 (element not found). -
Calculate
mid = (low + high)/2
. -
If
arr[mid] == key
, returnmid
. -
If
key < arr[mid]
, search inlow
tomid-1
. -
If
key > arr[mid]
, search inmid+1
tohigh
.
📈 Time Complexity
Case | Complexity |
---|---|
Best Case | O(1) |
Average Case | O(log n) |
Worst Case | O(log n) |
- Much faster than linear search, especially for large datasets.
✏️ Example
Array:
[5, 10, 15, 20, 25, 30, 35]Search for 20
:
- low = 0, high = 6
mid = (0+6)/2 = 3 → arr[3]=20
-
Found at index 3 🎯
Search for 40
:
- low = 0, high = 6
mid = (0+6)/2 = 3 → arr[3]=20
40 >20 search in upper half
low=mid+1=3+1=4
mid=(4+6)/2=5; arr[5]=30
40>30 search in upper half
low=mid+1=5+1=6
mid=(6+6)/2=6; arr[6]=35
40>35 search in upper half
low=mid+1=6+1=7
low >high stop; element not found
Key Points
-
Binary Search requires the array to be sorted.
-
It is very efficient compared to linear search.
-
Each comparison halves the search space!
Comments
Post a Comment