Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: Write a Python function to implement the binary search algorithm.
Answer:

def binary_search(arr, target):

  low, high = 0, len(arr) - 1

  while low <= high:

    mid = (low + high) // 2

    if arr[mid] == target:

      return mid

    elif arr[mid] < target:

      low = mid + 1

    else:

      high = mid - 1

    return -1

Example:

binary_search([1, 2, 3, 4, 5, 6, 7], 4)  # Output: 3
Is it helpful? Yes No

Most helpful rated by users:

©2025 WithoutBook