DSA Binary Search

DSA Tutorial

 DSA Binary Search – Complete Beginner Guide

(Concept • Manual Run-Through • Algorithm • Code • Time Complexity)

Binary Search is a fast and efficient searching algorithm in Data Structures & Algorithms (DSA).
It works by dividing the search space into halves.


1️⃣ What is Binary Search?

Binary Search:

  • Works only on sorted arrays

  • Compares the target with the middle element

  • Eliminates half of the search space each step

  • Repeats until element is found or range becomes empty

 Also called Half-Interval Search.


2️⃣ Simple Idea (One Line)

Check middle → discard half → repeat


3️⃣ When to Use Binary Search?

✔ Array must be sorted
✔ Large datasets
✔ Faster than Linear Search

❌ Unsorted arrays (must sort first)


4️⃣ Binary Search – Manual Run-Through

 Sorted Array

[3, 7, 11, 15, 18, 22, 30]

 Target Value

15

Step 1

low = 0, high = 6
mid = (0 + 6) / 2 = 3
arr[mid] = 15

Match Found

 Element found at index 3.


Another Example (Not Found Case)

Target = 10

StepmidValueAction
1315Search left
217Search right
3211Search left
Not found

5️⃣ Binary Search Algorithm (Steps)

  1. Start

  2. Set low = 0, high = n - 1

  3. While low ≤ high

  4. Calculate mid = (low + high) / 2

  5. If arr[mid] == key → return index

  6. If arr[mid] > key → search left half

  7. Else → search right half

  8. If not found → return -1

  9. Stop


6️⃣ Pseudocode

low = 0
high = n – 1while low <= high
mid = (low + high) / 2
if arr[mid] == key
return mid
else if arr[mid] > key
high = mid – 1
else
low = mid + 1
return -1

7️⃣ Binary Search Implementation (C++)

 Iterative Method


 

Output

Element found at index 3

8️⃣ Recursive Binary Search


 


9️⃣ Time Complexity

CaseTime Complexity
Best CaseO(1)
Average CaseO(log n)
Worst CaseO(log n)

 Each step reduces search space by half.


🔟 Space Complexity

MethodSpace
IterativeO(1)
RecursiveO(log n) (call stack)

1️⃣1️⃣ Advantages of Binary Search

✔ Very fast
✔ Efficient for large datasets
✔ Minimal comparisons


1️⃣2️⃣ Disadvantages of Binary Search

❌ Requires sorted data
❌ Not suitable for linked lists
❌ Sorting overhead if data is unsorted


1️⃣3️⃣ Binary Search vs Linear Search

FeatureLinearBinary
Sorted dataNot requiredRequired
TimeO(n)O(log n)
SpeedSlowFast
Use caseSmall dataLarge data

 Exam / Interview Questions (Binary Search)

Q1. Why is Binary Search faster?
👉 It halves the search space each step

Q2. Can Binary Search work on unsorted array?
👉 No

Q3. Best case time complexity?
👉 O(1)


Final Summary

✔ Binary Search works on sorted arrays
✔ Divide-and-conquer strategy
✔ Time complexity: O(log n)
✔ Space complexity: O(1) iterative
✔ Essential for DSA & interviews

You may also like...