Sobes.tech
Junior — Middle

Explain the working principle of the binary search algorithm and its main steps.

sobes.tech AI

Answer from AI

The binary search algorithm is used for quickly finding an element in a sorted array. Its principle is based on dividing the search area in half at each step.

Main steps:

  1. Determine the middle of the current search range.
  2. Compare the target element with the element in the middle.
  3. If they are equal — the element is found.
  4. If the target element is less than the middle, repeat the search in the left half.
  5. If it is greater — in the right half.
  6. Repeat until the range becomes empty.

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  # element not found

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