Binary search in a sorted array

This technical problem involves finding the index of a target value in a sorted array. If the target value is not present in the array, the function should return -1.

Problem

Given a sorted array of integers and a target value, find the index of the target value in the array. If the target value is not present in the array, return -1.
Example input: [1, 2, 3, 4, 5], 4
Example output: 3

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def find_index(array, target):
    # Binary search is the optimal solution for this problem.
    # It is optimal because it is O(log n) time complexity.
    # This is because the array is sorted and we can use the
    # divide and conquer approach to find the target value.
    # We can do this by finding the midpoint of the array and
    # comparing the target value to the midpoint. If the target
    # value is less than the midpoint, we can search the left
    # half of the array. If the target value is greater than
    # the midpoint, we can search the right half of the array.
    # We can repeat this process until we find the target value.
    # If we do not find the target value, we can return -1.
    left = 0
    right = len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] == target:
            return mid
        elif array[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

print(find_index([1, 2, 3, 4, 5], 4))
print(find_index([1, 2, 3, 4, 5], 6))

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The candidate has correctly identified binary search as the optimal solution for this problem and has implemented it correctly. The candidate's approach is clear and easy to follow.

Evaluated at: 2022-11-11 08:15:40