Find index of element in sorted array

This problem deals with finding the index of an element in a sorted array of integers. The input is a sorted array of integers and an integer value to find. The output is the index of the value in the array, or -1 if the value is not present in the array.

Problem

Implement a method to find the index of an element in a sorted array of integers.
Input: A sorted array of integers and an integer value to find.
Output: The index of the value in the array, or -1 if the value is not present in the array.

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use binary search.
// Binary search is optimal because it reduces the number of comparisons needed to find the index of the value in the array.
// Binary search works by dividing the array in half and comparing the value to the middle element.
// If the value is less than the middle element, the search continues on the left half of the array.
// If the value is greater than the middle element, the search continues on the right half of the array.
// This process continues until the value is found or the array is empty.

function binarySearch(array, value) {
  let start = 0;
  let end = array.length - 1;
  let middle = Math.floor((start + end) / 2);

  while (array[middle] !== value && start <= end) {
    if (value < array[middle]) {
      end = middle - 1;
    } else {
      start = middle + 1;
    }
    middle = Math.floor((start + end) / 2);
  }

  return array[middle] === value ? middle : -1;
} console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)); // 4
console.log(binarySearch([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11)); // -1

A.I. Evaluation of the Solution

The candidate's solution is correct and uses binary search, which is the most efficient way to search a sorted array for a specific value. The candidate's code is well-written and easy to understand.

Evaluated at: 2022-12-07 00:15:56