Sobes.tech
Junior

Which algorithm has logarithmic complexity O(log n)?

sobes.tech AI

Answer from AI

Binary Search.

The binary search algorithm efficiently finds an element in a sorted array by dividing it in half at each step. As a result, the execution time grows proportionally to the logarithm of the input size (n).

# Python
def binary_search(arr, target):
    low = 0
    high = len(arr) - 1

    while low <= high:
        mid = (low + high) // 2  # Find the middle element
        if arr[mid] == target:
            return mid  # Element found
        elif arr[mid] < target:
            low = mid + 1  # Ignore the left half
        else:
            high = mid - 1  # Ignore the right half

    return -1  # Element not found