Sobes.tech
Junior — Middle

Explain the principle and sequence of actions when using the binary search algorithm.

sobes.tech AI

Answer from AI

The binary search algorithm is used to find an element in a sorted array. The working principle:

  1. The middle element of the array is determined.
  2. If the sought element equals the middle, the search is successful.
  3. If the sought element is less than the middle, the search continues in the left half of the array.
  4. If it is greater, in the right half.
  5. The process repeats recursively or iteratively until the element is found or there is no subarray left for searching.

Example in Python:


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

# Usage
arr = [1, 3, 5, 7, 9]
print(binary_search(arr, 7))  # Will output index 3