Iterative Binary Search & Complexity Analysis in Python

⚡ Direct Answer & Key Takeaway

Iterative binary search locates a target in a sorted list by maintaining `low = 0` and `high = len(arr) - 1`, looping `while low <= high:`. Each iteration checks `mid = (low + high) // 2`: if `arr[mid] == target`, it returns `mid`; if `arr[mid] < target`, it sets `low = mid + 1`, else `high = mid - 1`. Halving the search interval each step gives O(log₂ n) worst-case time and O(1) auxiliary space.

1. Precondition and Boundary Pointer Mechanics

Binary search works exclusively on monotonic—typically ascending—sorted sequences because discarding half the array relies on order transitivity. If `arr` is unsorted, comparisons at `mid` give misleading directions and silently return `-1` even when the target exists. Start with inclusive bounds `low = 0` and `high = len(arr) - 1`, and keep the loop guard `while low <= high:`. Using `<` instead of `<=` is a classic CBSE bug: when `low == high`, one valid element remains unchecked and is wrongly skipped. Equally critical are the updates `low = mid + 1` and `high = mid - 1`. Writing `low = mid` or `high = mid` risks an infinite loop when the window shrinks to two elements and `mid` stalls on `low`.

  • Always verify the input list is sorted before invoking binary search.
  • Use `// 2` integer floor division so `mid` is always a valid integer index.
  • Update bounds strictly past `mid` (`mid + 1` or `mid - 1`) to guarantee termination.

2. Step-by-Step Dry Run on Found and Missing Targets

Examiners love asking for the exact sequence of `(low, high, mid)` values on a 7- or 9-element list. Suppose `arr = [12, 18, 25, 34, 42, 56, 68, 75]` (indices `0..7`) and `target = 56`. In Pass 1, `low = 0, high = 7`, so `mid = (0 + 7) // 2 = 3`; `arr[3]` is `34 < 56`, moving `low` to `4`. In Pass 2, `low = 4, high = 7`, giving `mid = 5`; `arr[5]` equals `56`, returning index `5` in just two probes. When searching for a missing value like `30`, the bounds narrow until `low > high`, cleanly exiting the loop and returning `-1` to signal absence without raising an index error. Contrast this with linear search, which would inspect all eight elements before reporting `-1`.

  • Trace `(low, high, mid, arr[mid])` row-by-row in exam dry-run questions.
  • Return `-1` when `low > high` to indicate the target is absent from the sorted list.
  • Even-length slices have two middle indices; `(low + high) // 2` picks the left-middle element.

3. Time and Space Complexity Compared to Linear Search

Because each unsuccessful comparison halves the remaining candidate range from `n` to `n/2`, then `n/4`, down to `1`, the maximum number of iterations satisfies `2^k >= n`, or `k <= ⌊log₂ n⌋ + 1`. On a sorted array of `1,024` records, linear search may need `1,024` comparisons in the worst case, whereas iterative binary search finishes in at most `11` comparisons. Best-case time is `O(1)` when the initial `mid` matches the target immediately, while average and worst-case times are `O(log n)`. Unlike recursive binary search—which consumes `O(log n)` call-stack frames—iterative binary search stores only three integer variables (`low`, `high`, `mid`), achieving strict `O(1)` auxiliary space complexity. If the list is unsorted and searched only once, sorting first takes `O(n log n)`, making linear search faster overall.

  • Best-case time is `O(1)` when the first `mid` element matches `target`.
  • Worst-case comparisons scale as `⌊log₂ n⌋ + 1`, giving `O(log n)` time.
  • Iterative implementation uses `O(1)` auxiliary space compared to `O(log n)` stack space for recursion.

4. Iterative Binary Search with Comparison Counter on Sorted List

def binary_search(arr, target):
    low, high = 0, len(arr) - 1
    steps = 0
    while low <= high:
        steps += 1
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid, steps
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1, steps

data = [12, 18, 25, 34, 42, 56, 68, 75]
for q in (56, 12, 30):
    idx, probes = binary_search(data, q)
    print(f"Target {q}: index={idx}, comparisons={probes}")

Verified Console / Dry-Run Output:

Target 56: index=5, comparisons=2
Target 12: index=0, comparisons=3
Target 30: index=-1, comparisons=3

5. Search Algorithm Preconditions and Complexity Comparison

AlgorithmPreconditionBest / Worst TimeAuxiliary Space
Linear SearchNone (works unsorted)O(1) / O(n)O(1)
Iterative Binary SearchSorted sequenceO(1) / O(log n)O(1)
Recursive Binary SearchSorted sequenceO(1) / O(log n)O(log n) call stack
Sort + Binary Search (1 query)Unsorted sequenceO(n log n) / O(n log n)O(n) (Timsort)
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Algorithms 1-on-1 with 4Achievers Junior

Sharpen searching, dry runs, and time-complexity reasoning for CBSE Class 11-12 CS (083) with 4Achievers Junior (Grades 3-12) in 1-on-1 or 1:4 Micro-Pods.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Running binary search on an unsorted list without sorting it first, causing missed targets.
  • Avoid Mistake: Writing `while low < high:` instead of `while low <= high:`, which skips the final single-element window when `low == high`.
  • Avoid Mistake: Updating `low = mid` or `high = mid` instead of `mid + 1` or `mid - 1`, causing an infinite loop on 1- or 2-element subarrays.
  • Avoid Mistake: Using single-slash division `(low + high) / 2` instead of integer floor division `// 2`, producing a `TypeError` when indexing `arr[mid]`.
  • Examiner / Mentor Tip: If a descending-order list is given in a CBSE problem, flip the inequalities: update `high = mid - 1` when `arr[mid] < target`.
  • Examiner / Mentor Tip: State both `O(log n)` time and `O(1)` space when comparing iterative binary search against its recursive version in viva.
  • Examiner / Mentor Tip: Check 0-based indexing carefully—returning `mid` gives the index, whereas `mid + 1` gives the 1-based position.

7. Interactive Concept Check Quiz

Question: In `arr = [5, 10, 15, 22, 27, 35]`, how many comparisons does iterative binary search make to find `27`, and what index is returned?

8. Frequently Asked Questions

Can iterative binary search work on an unsorted Python list?
No. Binary search relies on comparing `arr[mid]` to discard either the left or right half; on an unsorted list, the target could lie in the discarded half.
Why must the loop condition be low <= high instead of low < high?
If `low == high` holds the target (for example searching for `12` when `low = 0, high = 0`), `<` exits early and wrongly returns `-1`. Using `<=` ensures that final element is checked.
Why do we update low = mid + 1 and high = mid - 1 instead of mid?
Because `mid` has already been tested and is not equal to `target`. Moving to `mid + 1` or `mid - 1` shrinks the window strictly and prevents infinite loops.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class