Binary search in a sorted array

Given a sorted array of integers, this function returns the index of a given target value. If the target value is not present in the array, it returns -1.

Problem

Given a sorted array of integers, write a function that returns the index of a given target value. If the target value is not present in the array, return -1.
Example input: [1, 2, 3, 4, 5], target = 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, target):
    for i in range(len(array)):
        if array[i] == target:
            return i
    return -1

# This solution is optimal because it is O(n) time complexity.
# It is O(n) because it iterates through the array once.
# It is not O(n^2) because it does not iterate through the array twice.
# It is not O(log n) because it does not divide the array in half.
# It is not O(1) because it does not return the first element of the array.

A.I. Evaluation of the Solution

This solution is correct and demonstrates a good understanding of time complexity.

Evaluated at: 2022-11-10 02:15:47