Skip to main content
Data Structures & Algorithms Beginner Practical Coding Topic: Binary Search

Why does mid = (left + right) / 2 fail in Binary Search and how do you fix it?

Quick Summary: In fixed-width signed 32-bit languages (Java/C++), adding left + right when both exceed 1.07 billion overflows Integer.MAX_VALUE negative and crashes indexing; computing left + (right - left) / 2 or (left + right) >>> 1 prevents overflow while keeping O(log n) time.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

Even when an array stays valid within memory, computing (left + right) / 2 sums two indices before dividing—wrapping past 2,147,483,647 into negative integers and throwing ArrayIndexOutOfBoundsException.

Using int mid = left + (right - left) / 2; (or unsigned shift (left + right) >>> 1 in Java) computes the exact midpoint safely for all valid indices.

Detailed Technical Explanation

Pair safe midpoint arithmetic with a strict loop invariant: for inclusive bounds [left, right], use while (left <= right) and always update boundaries by mid + 1 or mid - 1 so the search space shrinks strictly every iteration without infinite loops.

Practical Walkthrough

Canonical overflow-safe Java binary search returning target index or -1.

Code Example — JAVA
public class SafeBinarySearch {
    public static int search(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) return mid;
            if (nums[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1;
    }
}
Expected Output / Verification
Strict O(log n) time, O(1) space, zero integer overflow risk.

Real-World Production Use Case

Log timestamp bisecting, database B-Tree page search, and capacity optimization problems ("Binary Search on Answer").

Common Interview Mistakes to Avoid

  • Writing while (left < right) with right = mid - 1, accidentally skipping the final single element check.
  • Using (left + right) / 2 in Java/C++ interviews on large search bounds.
Topics: #dsa #binary-search #java #complexity
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.