Binary Search

Given a sorted array of integers and a target value, this function will return the index of the target value if found, or -1 if not found.

Problem

Given a sorted array of integers and a target value, return the index of the target value if found, or -1 if not found.
Input: [1, 2, 3, 4, 5], 3
Output: 2

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def find_target(arr, target):
    # Binary search
    # O(log n)
    # The array is sorted, so we can use binary search to find the target
    # in O(log n) time.
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The candidate has used binary search, which is the most efficient way to search a sorted array for a target value.

Evaluated at: 2022-11-05 01:19:43