Binary search in a sorted array

This technical problem deals with the binary search algorithm, specifically searching for a given key in a sorted array. The function should return the index of the key if it is found, or -1 if it is not found.

Problem

Given a sorted array of integers, write a function that returns the index of the given key. If the array does not contain the key, return -1.
Example input: [1, 2, 3, 4, 5], key = 3
Example output: 2

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def find_index(array, key):
    # Binary search
    # O(log n)
    low = 0
    high = len(array) - 1
    while low <= high:
        mid = (low + high) // 2
        if array[mid] == key:
            return mid
        elif array[mid] < key:
            low = mid + 1
        else:
            high = mid - 1
    return -1

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

A.I. Evaluation of the Solution

The candidate's solution correctly implements a binary search algorithm to find the index of a given key in a sorted array. The solution is efficient and correctly returns the index of the key if it is present in the array, or -1 if it is not.

Evaluated at: 2022-11-12 04:16:15