Binary Search Visualizer
Watch how Binary Search efficiently finds elements in O(log n) time by dividing the search space in half
Array Size: 9Comparisons: 0
11
[0]
22
[1]
33
[2]
44
[3]
55
[4]
66
[5]
77
[6]
88
[7]
99
[8]
In Range
Left Pointer
Mid (Checking)
Right Pointer
Comparing
Found!
Eliminated

Binary Search Implementation:

public static int binarySearch(int[] arr, int target) {
    int left = 0;
    int right = arr.length - 1;
    
    while (left <= right) {
        int 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
}

// Time Complexity: O(log n)
// Space Complexity: O(1)
// Prerequisite: Array must be SORTED!

⚠️ Important Prerequisites:

  • Array must be SORTED in ascending order
  • Binary search only works on sorted data
  • Each iteration eliminates half of the remaining elements
  • Much faster than linear search for large datasets