Skip to content
TeachTrails
DSAAlgorithms

Binary Search Algorithm Explained (Time Complexity + Code)

Binary search explained for beginners: how it works step by step, why its time complexity is O(log n), code in Python, Java and C++, a visual demo and a memory trick.

Sudipta Biswas, AI Engineer

9 min read

Beginner friendly
Find 23 in a sorted listStep 12581216mid2338567291Step 22581216233856mid7291Step 3258121623FOUND38567291

The binary search algorithm is the fastest way to find an item in a sorted list, and one of the first algorithms every computer science student learns. It's also an interview favourite, because it's short to write but easy to get subtly wrong.

In this guide you'll see how binary search works step by step, why its time complexity is O(log n), working code in Python, Java and C++, and a memory trick so you never forget the rules.

Try it first: the guessing game

Before any theory, play this. You're about to watch binary search beat you at a game.

🎯 I'll guess your number in 7 tries

Think of a whole number from 1 to 100. Don't tell me. Just answer honestly.

Guess #1 · searching 1–100 (100 left)

Is it 50?

1remaining range100

That's binary search. The computer never guessed randomly; it always picked the middle of what was left, so every answer cut the possibilities in half.

What is binary search?

Binary search is a searching algorithm that finds a target value in a sorted array by repeatedly dividing the search range in half. It compares the target with the middle element:

  • If they're equal, you're done.
  • If the target is bigger, it can only be in the right half, so ignore the left.
  • If the target is smaller, it can only be in the left half, so ignore the right.

How binary search works, step by step

  1. Set two pointers: low at the first index and high at the last.
  2. While low ≤ high, find the middle: mid = (low + high) / 2 (rounded down).
  3. If arr[mid] equals the target, return mid.
  4. If arr[mid] is smaller than the target, set low = mid + 1.
  5. Otherwise, set high = mid - 1.
  6. If low passes high, the target isn't there: return -1.

👣 Step through binary search

Search for:
0
3
low
1
7
2
11
3
15
4
19
5
24
6
28
7
33
8
41
9
47
10
52
11
60
12
66
13
75
14
88
high

Step 1/9: Looking for 41. The array is sorted, so we can use binary search. low = 0, high = 14.

checking midruled outfound

Binary search code (Python, Java, C++)

Iterative binary search
def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid            # found: return the index
        elif arr[mid] < target:
            low = mid + 1         # target is in the right half
        else:
            high = mid - 1        # target is in the left half
    return -1                     # not found

nums = [3, 7, 11, 15, 19, 24, 28, 33, 41]
print(binary_search(nums, 24))   # 5
print(binary_search(nums, 50))   # -1

Binary search time complexity

Every comparison halves the remaining items. Starting from n items, after k steps you have n / 2ᵏ left. You're done when that reaches 1, so k = log₂(n). That's why binary search is O(log n). (New to this notation? Read Big O notation explained.)

Best caseO(1): the first middle element is the target
Average caseO(log n)
Worst caseO(log n): item is at an end or missing
Space (iterative)O(1)
Space (recursive)O(log n): one stack frame per halving

To feel how fast that is: linear search through a billion sorted items could take a billion comparisons. Binary search needs about 30.

🧠 PATH memory card

Remember binary search for good

Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.

  1. P

    Picture it

    Your brain remembers scenes far better than definitions.

    Open middle: LM is after L → drop left halfMiddle of rest: PM is before P → drop right partMiddle: M ✓Found “mango” in 3 looks

    ← swipe to see the whole picture →

    Looking up “mango” in a paper dictionary: you never read from page 1. You open the middle, see “L”, ignore everything before it, open the middle of what's left, and land on “M” in a few looks.

  2. A

    Anchor it

    A silly sentence you can't forget, where every word maps to the concept.

    “Sorted → Middle → Halve (if it's not Sorted, just Shake My Head)”

    • Sorted→Only works on sorted data. Check this first!
    • Middle→Always compare with the middle element
    • Halve→Drop the half that can't hold the target, repeat
    • SMH→Sorted, Middle, Halve: the 3 steps in order
    • 10 for a thousand→About 10 steps for 1,000 items
    • 20 for a million→About 20 steps for 1,000,000 items, so O(log n)
  3. T

    Trace it

    Run it by hand on a tiny example once. Doing beats reading.

    Find 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]: mid index 4 → 16 (too small, go right) → mid index 7 → 56 (too big, go left) → mid index 5 → 23 ✓. Three looks out of ten items. Write the low/mid/high values on paper once.
  4. H

    Hit-recall it

    Test yourself now, then again on the day each card comes back.

    Card 1 / 8 · new0 mastered · 0 practised

    Say the answer out loud first, then flip and be honest.

Linear search vs binary search

  • Linear search: works on any list, checks items one by one, O(n).
  • Binary search: needs sorted data, halves the range each step, O(log n).
  • If you search an unsorted list only once, linear search is fine. If you search many times, sort once (see our sorting algorithms guide) and binary search after.

What to learn next

Binary search is the foundation for binary search trees and many “search on the answer” interview problems. Next, learn the two everyday data structures in stack vs queue.

Key takeaways

  • Binary search only works on sorted data.
  • Compare with the middle, throw away the half that can't contain the target, repeat.
  • Time complexity is O(log n): about 20 steps for a million items.
  • Use low ≤ high, and move pointers to mid + 1 or mid - 1 to avoid infinite loops.
  • Remember it with “Sorted → Middle → Halve.”

Frequently asked questions

What is binary search in simple words?

Binary search finds an item in a sorted list by repeatedly checking the middle element and throwing away the half that cannot contain the target. Each step halves the search space, so it finds items very quickly.

What is the time complexity of binary search?

Binary search runs in O(log n) time in the average and worst case, and O(1) in the best case (when the middle element is the target). The iterative version uses O(1) extra space; the recursive version uses O(log n) space for the call stack.

Why does binary search need a sorted array?

Because it decides which half to throw away by comparing the target with the middle element. That decision is only correct if everything on the left is smaller and everything on the right is larger, which is true only when the data is sorted.

What is the difference between linear search and binary search?

Linear search checks items one by one and works on any list, taking O(n) time. Binary search needs sorted data but takes only O(log n) time: about 20 steps for a million items instead of up to a million.

Why do people write mid = low + (high - low) / 2?

In languages with fixed-size integers like Java and C++, (low + high) can overflow when both are very large. low + (high - low) / 2 gives the same middle without overflowing. Python integers don't overflow, so (low + high) // 2 is fine there.

🧠 Quick check: binary search

  1. 1. What must be true about the data before you use binary search?

  2. 2. What is the worst-case time complexity of binary search?

  3. 3. Roughly how many steps does binary search need for 1,000,000 sorted items?

  4. 4. arr[mid] is smaller than the target. What should you do?

DSA for Beginners

Part 3 of 4: Binary Search Algorithm Explained