Sobes.tech
Senior

What is the algorithmic complexity of binary search in a sorted array?

sobes.tech AI

Answer from AI

The algorithmic complexity of binary search in a sorted array is O(log n), where n is the number of elements in the array.

This is because at each step, the algorithm divides the search area in half, reducing the number of considered elements by 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
}