Sobes.tech
Junior — Middle

How is the time complexity of binary search determined?

sobes.tech AI

Answer from AI

The time complexity of the binary search algorithm is O(log n), where n is the number of elements in the sorted array. This is because at each step, the algorithm divides the search area in half, reducing the number of considered elements by a factor of two, until it finds the target element or confirms its absence.

Example in Go:

func binarySearch(arr []int, target int) int {
    left, right := 0, len(arr)-1
    for left <= right {
        mid := left + (right-left)/2
        if arr[mid] == target {
            return mid
        } else if arr[mid] < target {
            left = mid + 1
        } else {
            right = mid - 1
        }
    }
    return -1 // element not found
}
How is the time complexity of binary search… - sobes.tech