Binary Search: Search a Sorted Array of Integers

This problem asks you to write a function that searches a sorted array of integers for a given value. If the value is found, the function should return the index where it is located. If the value is not found, the function should return -1.

Problem

Given a sorted array of integers, write a function called search() that accepts a value and returns the index where the value passed to the function is located. If the value is not found, return -1.
Example input: [1,2,3,4,5,6,7], 2
Example output: 1

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
def search(arr, val):
    # Binary search is the optimal solution for this problem.
    # It is optimal because it is a divide and conquer algorithm
    # that reduces the search space by half each time.
    # This means that the time complexity is O(log n)
    # The space complexity is O(1)
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == val:
            return mid
        elif arr[mid] < val:
            low = mid + 1
        else:
            high = mid - 1
    return -1

print(search([1,2,3,4,5,6,7], 2))

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The candidate has correctly identified that binary search is the optimal solution for this problem. The candidate's implementation of binary search is also correct. The only thing that could be improved is the candidate's explanation of the time and space complexity of the solution. The candidate correctly states that the time complexity is O(log n), but does not explain why. The candidate also correctly states that the space complexity is O(1), but again does not explain why.

Evaluated at: 2022-11-21 12:16:24