❖ What is Binary Search?
Binary Search
is an efficient searching algorithm used to find the position of a target element in a sorted array or data structure. It follows the Divide and Conquer
approach, where the algorithm repeatedly divides the search interval in half.
🔍 Is Binary Search used to find a specific element?
✅ Yes!
Binary Search helps you quickly find the position of a target value in a sorted list.
For example, if you want to find the number 45
in a sorted list, binary search can find it in just a few steps — even if the list has millions of numbers.
⚡ Why use Binary Search instead of Linear Search?
🔸 Feature | 🐢 Linear Search | ⚡ Binary Search |
---|---|---|
List needs to be sorted | ❌ No | ✅ Yes |
How it works | Checks one by one | Cuts search range in half |
Speed (large data) | Slower (O(n) ) | Much faster (O(log n) ) |
Example (1 million items) | Up to 1,000,000 steps | Around 20 steps only |
🔃 Sorting Prerequisite for Binary Search
Binary Search only works on sorted data.
If your array or list is not already sorted, you must sort it first before using binary search.
🔧 Common Sorting Algorithms:
Here are some popular sorting algorithms used to prepare data for binary search:
Algorithm | Description |
---|---|
Quick Sort | Very fast on average; uses divide-and-conquer strategy |
Merge Sort | Stable and predictable performance; also uses divide-and-conquer |
Heap Sort | Based on binary heap data structure; good worst-case time complexity |
TimSort | Hybrid of Merge + Insertion sort; used in Python and Java (built-in) |
Insertion Sort | Simple and efficient for small or nearly sorted datasets |
Selection Sort | Easy to understand, but slower on large datasets |
🔍 What Binary Search Does
Binary Search is a fast and efficient algorithm to find a specific element (like a number or word) in a sorted list or array.
Instead of checking every element one by one like in Linear Search, binary search works by repeatedly dividing the list in half, drastically reducing the number of comparisons.
🧠 How It Works (Step-by-Step)
Binary Search follows these steps:
- Start with two pointers:
left = 0 right = n - 1
- Repeat while
left
is less than or equal toright
:
- Calculate the middle index:
mid = (left + right) / 2
👉 In code, use mid = left + (right - left) // 2
to avoid overflow in some languages.
- Compare the middle element with the target:
if arr[mid] == target: return mid # 🎯 Target found! elif arr[mid] < target: left = mid + 1 # 🔍 Search in the right half else: right = mid - 1 # 🔍 Search in the left half
- If no match is found, return -1 (or indicate not found).
🔁 What’s Happening at Each Step
Step | Explanation |
---|---|
left = 0 | Start of the array |
right = n - 1 | End of the array |
mid = (left + right)/2 | Checks the middle element |
arr[mid] < target | Target must be on the right → move left |
arr[mid] > target | Target must be on the left → move right |
arr[mid] == target | 🎉 Target found! Return the index |
left > right | Search space is empty → target not in array |
📘 Practical Uses of Binary Search
🔍 1. Looking Up Words in a Dictionary
If you search for a word in a digital dictionary, binary search helps find it fast because the words are already sorted (A–Z).
📁 2. Searching in Sorted Databases
In apps like contacts, banking, or online stores, data is often sorted. Binary search helps to find records quickly, like a name or product.
🐞 3. Debugging Code (e.g., git bisect
)
When a bug appears in your code, tools like git bisect
use binary search to find the exact version where the bug started — by checking the middle point each time.
📈 4. Solving Optimization Problems
Example: You need to find the minimum internet speed to stream videos without buffering.
Binary search helps by testing different speeds, adjusting higher or lower based on results — until it finds the best one.
🧠 5. Finding an Item in a List
Whenever you want to find a number or name in a sorted list, binary search checks the middle, then narrows the search — much faster than looking at every item.
🕒 6. Finding First or Last Occurrence
Example: In a sorted list of dates or numbers, binary search can help you find the first time something happened or the last time it appeared.
✍️ 7. Autocomplete and Spell Check
When you type a few letters, binary search helps quickly find all matching words in a sorted word list — speeding up autocomplete and spell check.
🧾 8. Searching in Huge or Unknown Data
Even if the list is very large or you don’t know its full size, binary search can still work by smartly guessing the range and then applying its method.
__
⚠️ Preconditions & Constraints
To use binary search correctly, the following conditions must be met:
1. ✅ Sorted Data Required
The list or array must be sorted — either in ascending or descending order.
(Binary search won’t work on unsorted data.)
2 ✅ Random Access Needed
You must be able to access any element directly by index (e.g., arr[5]
).
This means arrays or lists, not linked lists (which require sequential access).
3 ❌ Data Must Not Change During Search
The data should stay the same during the search.
If elements are added, removed, or changed, the search may give incorrect results.
__
🧮 Binary Search Formula
To perform binary search, we repeatedly divide the search range in half to find the target value quickly in a sorted array or list.
m = (l + r) / 2
Where:
-
l
is theleft boundary
(starting index of the current range) -
r
is theright boundary
(ending index of the current range) -
m
is themiddle index
, where we check the current element
__
8. 🔎 Step-by-Step Example of Binary Search
Let's walk through how Binary Search works using a simple example.
Array: [-1, 0, 3, 5, 9, 12] Indexes: 0 1 2 3 4 5 Target: 9
We want to find the index of 9
in the array.
⚙️ Initial Setup
We begin by setting two pointers:
left = 0 // First index of the array right = 5 // Last index (n - 1), where n = 6
To find the middle index, we use the formula:
mid = (left + right) / 2
In code
mid = Math.floor((left + right) / 2);
This gives us the index of the middle element.
🔁 Iteration-by-Iteration Process
✅ 1st Iteration
left = 0 right = 5 mid = (0 + 5) / 2 = 2 arr[mid] = 3
arr[mid] = 3
- Target is
9
➡️ 3 < 9
→ So, we search the right half.
Update pointers:
left = mid + 1 = 3 right = 5
✅ 2nd Iteration:
left = 3 right = 5 mid = (3 + 5) // 2 = 4 arr[mid] = 9
arr[mid] = 9
Target is 9 → ✅ Found!
9. ✅ Three Decision Cases in Binary Search
At each step in Binary Search, we compare the middle element (arr[mid]
) with the target.
There are only three possible outcomes, and each one tells us exactly what to do next:
1️⃣ arr[mid] == target
→ 🎯 Element Found
- The middle element is equal to the target.
- ✅ Return
mid
(we found the target's index).
if (arr[mid] === target) { return mid; }
2️⃣ arr[mid] < target → 🔍 Search Right Half
- The middle element is smaller than the target.
- So the target must be in the right half.
- ❗ Move the left pointer to mid + 1.
else if (arr[mid] < target) { left = mid + 1; }
3️⃣ arr[mid] > target → 🔍 Search Left Half
- The middle element is greater than the target.
- So the target must be in the left half.
- ❗ Move the right pointer to mid - 1.
else { right = mid - 1; }
10. 🧾 Pseudocode
Binary Search can be implemented in two ways:
- 🔁 Iterative (using a loop)
- 🔂 Recursive (function calling itself)
🔁 Iterative Binary Search (Pseudocode)
function binarySearch(arr, target): left = 0 right = length(arr) - 1 while left <= right: mid = (left + right) // 2 if arr[mid] == target: return mid // 🎯 Found else if arr[mid] < target: left = mid + 1 // 🔍 Search right half else: right = mid - 1 // 🔍 Search left half return -1 // ❌ Not found
🔂 Recursive Binary Search (Pseudocode)
function binarySearch(arr, left, right, target): if left > right: return -1 // ❌ Base case: not found mid = (left + right) // 2 if arr[mid] == target: return mid // 🎯 Found else if arr[mid] < target: return binarySearch(arr, mid + 1, right, target) // Search right else: return binarySearch(arr, left, mid - 1, target) // Search left
11. 💻 Code Examples (JavaScript Only)
Binary Search in JavaScript using both:
- 🔁 Iterative method
- 🔂 Recursive method
🔁 Iterative Binary Search (JavaScript)
function binarySearch(arr, target) { let left = 0; let right = arr.length - 1; while (left <= right) { let mid = Math.floor((left + right) / 2); if (arr[mid] === target) { return mid; // 🎯 Found } if (arr[mid] < target) { left = mid + 1; // 🔍 Search right half } else { right = mid - 1; // 🔍 Search left half } } return -1; // ❌ Not found } // ✅ Example: const nums = [-1, 0, 3, 5, 9, 12]; console.log(binarySearch(nums, 9)); // Output: 4
🔂 Recursive Binary Search (JavaScript)
function binarySearchRecursive(arr, left, right, target) { if (left > right) { return -1; // ❌ Base case: not found } let mid = Math.floor((left + right) / 2); if (arr[mid] === target) { return mid; // 🎯 Found } if (arr[mid] < target) { return binarySearchRecursive(arr, mid + 1, right, target); // 🔍 Right half } else { return binarySearchRecursive(arr, left, mid - 1, target); // 🔍 Left half } } // ✅ Example: const arr = [-1, 0, 3, 5, 9, 12]; console.log(binarySearchRecursive(arr, 0, arr.length - 1, 9)); // Output: 4
13. 🔍 Linear Search vs. Binary Search Comparison
Let’s compare Linear Search and Binary Search — two fundamental searching algorithms.
⚖️ Time Complexity Comparison
Algorithm | Time Complexity | Sorted Required? |
---|---|---|
🔁 Linear Search | O(n) | ❌ No |
⚡ Binary Search | O(log n) | ✅ Yes |
-
n
= number of elements in the array - Linear Search checks each item one by one
- Binary Search cuts the search space in half each step
📌 When to Use Each
Use Case | Choose |
---|---|
✅ Unsorted data | Linear Search |
✅ Small datasets | Linear Search |
✅ Sorted array (ascending/descending) | Binary Search |
✅ Large datasets | Binary Search |
✅ Fast performance needed | Binary Search |
🚀 Why Binary Search is Better for Large Sorted Arrays
-
Linear Search:
- Worst-case: Checks all elements
- Example: 1,000,000 items → 1,000,000 comparisons 😓
-
Binary Search:
- Worst-case: Only about
log₂(n)
comparisons - Example: 1,000,000 items → Only ~20 steps 😎
- Worst-case: Only about
📊 Example: Searching for 9
in [1, 3, 5, 7, 9, 11, 13]
Step | Linear Search | Binary Search |
---|---|---|
1 | Check 1 | Check mid 7 |
2 | Check 3 | Move right, check 11 |
3 | Check 5 | Move left, check 9 ✅ |
4 | Check 7 | - |
5 | Check 9 ✅ | - |
14. 📚 Real-World “Dictionary Lookup” Analogy
One of the best ways to understand Binary Search is by imagining how you look up a word in a dictionary.
📖 Scenario:
You're trying to find the word "Tiger" in a large English dictionary.
How do you usually search?
- You don’t start from page 1 and go word by word — that would be like Linear Search 🐢.
- Instead, you open the dictionary to the middle — this is like Binary Search ⚡.
🧠 Step-by-Step Analogy:
Step | Action | What it Means in Binary Search |
---|---|---|
📄 1 | Open to the middle of the dictionary | Compute mid = (left + right)/2 |
🔍 2 | See a word like "Lamp" | Compare mid value to target |
➡️ 3 | "Lamp" comes before "Tiger" alphabetically | Move to the right half |
🔄 4 | Open to the middle of that right half | Recalculate mid |
✅ 5 | Eventually land on "Tiger" | Found the target! 🎯 |
📌 Key Idea:
Instead of checking every page (Linear Search), you narrow down the range by half every time — just like Binary Search in a sorted array.
17. ⚠️ Common Pitfalls & Edge Cases
Even though Binary Search is simple in concept, it’s easy to make mistakes in implementation. Here's what to watch out for:
🧱 1. Empty or Single-Element Arrays
- Always check if the array is empty before running the search.
- Binary Search can handle one-element arrays, but logic must still work.
// Example: binarySearch([], 5); // Should return -1 (not found) binarySearch([10], 10); // Should return 0
🔁 2. Duplicate Values
Binary Search returns any one index where the value exists — not guaranteed to be first or last.
If you need:
- First occurrence → search left even after finding target.
- Last occurrence → search right even after finding target.
// Array: [1, 2, 2, 2, 3] // Regular binary search might return index 2 // But first occurrence is at index 1
⚠️ 3. Integer Overflow in Mid Calculation
When using languages like C, C++, or Java, this can happen:
int mid = (left + right) / 2; // ❌ Can overflow if left + right is too large
✅ Safe alternative (also works in JavaScript):
let mid = left + Math.floor((right - left) / 2);
🔄 4. Infinite Loops
Forgetting to update left or right properly can cause infinite loops.
Always make sure your loop condition is:
while (left <= right)
And you’re updating pointers correctly:
-
left = mid + 1
if searching right -
right = mid - 1
if searching left
🧠 5. Off-by-One Errors
- Binary search boundaries can be tricky.
- Be careful with:
mid = Math.floor((left + right) / 2)
left <= right
vs. left < right
Top comments (0)