Binary Search

The problem is to find the index of a given target value in a sorted array of integers. If the target value is not found in the array, the function should return -1.

Problem

Given a sorted array of integers and a target value, write a function that returns the index of the target value if it is found in the array, or -1 if it is not found.
Example input: [1, 2, 3, 4, 5], 3
Example output: 2

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def find_target(array, target):
    for i in range(len(array)):
        if array[i] == target:
            return i
    return -1

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



This solution is optimal because it is O(n) time complexity.


A.I. Evaluation of the Solution

This solution is optimal because it is O(n) time complexity. However, it is not the most efficient solution. A more efficient solution would be to use a binary search, which would have a time complexity of O(log n).

Evaluated at: 2022-11-18 04:15:42