Binary search in a sorted array

The function should take a sorted array of integers and a target value as inputs, and return the index of the target value if it exists in the array, or -1 if it does not .

Problem

Given a sorted array of integers and a target value, write a function that returns the index of the target value if it exists in the array, or -1 if it does not.
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):
    
    This function takes in a sorted array and a target value.
    It returns the index of the target value if it exists in the array, or -1 if it does not.
    
    # This solution is optimal because it uses a binary search algorithm, which has a time complexity of O(log n).
    # This is optimal because the array is sorted.
    # If the array was not sorted, the time complexity would be O(n).
    # This is because we would have to iterate through the entire array to find the target value.
    # The space complexity is O(1) because we are not creating any new data structures.
    # We are only using variables to store the index of the target value.
    # If we were to create a new data structure, the space complexity would be O(n).
    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_target([1, 2, 3, 4, 5], 3))
print(find_target([1, 2, 3, 4, 5], 6))

A.I. Evaluation of the Solution

This is a well-detailed and complete solution to the problem. The candidate has correctly identified the time and space complexity of the solution and has provided a clear explanation of the approach. The candidate has also correctly implemented a binary search algorithm to solve the problem.

Evaluated at: 2022-11-28 06:16:27