Binary Search: Find the Target Value

This problem deals with finding a target value in a sorted array of integers. The function should return the index of the target value if it is found in the array, or -1 if it is not found.

Problem

Given a sorted array of integers, write a function that returns the index of the target value. If the target value is not found 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_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 only works if the array is sorted. If the array is not sorted, this solution will not work.

Evaluated at: 2022-11-04 19:44:20