Determining if a Value is Present in a Sorted Array

This problem deals with determining if a given value is present in a sorted array. An example input is given as [1, 3, 5, 7], 5, with the expected output being true.

Problem

Given a sorted array of integers, write a function to determine whether the array contains a given value.
Example input: [1, 3, 5, 7], 5
Example output: true

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use a binary search algorithm.
// This is optimal because it will always find the value in the array in O(log n) time.
// This is because the array is sorted, so we can eliminate half of the array each time we search.
// This is a recursive solution.

function binarySearch(arr, val) {
  if (arr.length === 0) {
    return false;
  }

  let mid = Math.floor(arr.length / 2);

  if (arr[mid] === val) {
    return true;
  } else if (arr[mid] > val) {
    return binarySearch(arr.slice(0, mid), val);
  } else {
    return binarySearch(arr.slice(mid + 1), val);
  }
}

console.log(binarySearch([1, 3, 5, 7], 5)); // true
console.log(binarySearch([1, 3, 5, 7], 6)); // false

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The candidate has correctly identified that the optimal solution is to use a binary search algorithm, and has correctly implemented a recursive binary search algorithm. The candidate's solution correctly returns true when the value is found in the array, and correctly returns false when the value is not found in the array.

Evaluated at: 2022-12-11 10:15:40