Binary Search | Python (original) (raw)

Last Updated : 20 Dec, 2025

Binary Search is an efficient searching algorithm used to find an element in a **sorted array by repeatedly dividing the search interval in half. It reduces the time complexity to O(log N), making it much faster than linear search.

Here is working of Binary Search

  1. Find the middle element of the array.
  2. Compare the middle element with the target key. If equal: return index.
  3. If the key is smaller: search the left half.
  4. If the key is larger: search the right half.
  5. Repeat until the element is found or the search space is empty.

Binary Search using the bisect

Python provides the bisect module, which offers built-in functions to maintain a list in sorted order and perform efficient binary searches internally.

Python `

import bisect

def binary_search_bisect(arr, x): i = bisect.bisect_left(arr, x) if i != len(arr) and arr[i] == x: return i else: return -1

arr = [2, 3, 4, 10, 40] x = 10 result = binary_search_bisect(arr, x)

if result != -1: print("Element is present at index", result) else: print("Element is not present in array")

`

Output

Element is present at index 3

**Explanation:

This version manually performs binary search using a while loop - efficient in both time and space.

Python `

def binary_search(arr, x): low = 0 high = len(arr) - 1

while low <= high:
    mid = low + (high - low) // 2

    if arr[mid] < x:
        low = mid + 1
    elif arr[mid] > x:
        high = mid - 1
    else:
        return mid
return -1

arr = [2, 3, 4, 10, 40] x = 10 result = binary_search(arr, x)

if result != -1: print("Element is present at index", result) else: print("Element is not present in array")

`

Output

Element is present at index 3

**Explanation:

Recursion simplifies the logic but increases memory usage due to function call stacks.

Python `

def binary_search(arr, low, high, x): if high >= low: mid = low + (high - low) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binary_search(arr, low, mid - 1, x) else: return binary_search(arr, mid + 1, high, x) else: return -1

arr = [2, 3, 4, 10, 40] x = 10

result = binary_search(arr, 0, len(arr) - 1, x)

if result != -1: print("Element is present at index", result) else: print("Element is not present in array")

`

Output

Element is present at index 3

**Explanation: