Binary Search

The "Binary Search" code problem asks the user to write a function that takes a sorted array of integers and a target value as input, and returns the index of the target value if it is present in the array. If the target value is not present in the array, the function should return -1.

Problem

Given a sorted array of integers, write a function that returns the index of a given target value. If the target value is not present in the array, the function should return -1.
Example input: [1, 2, 3, 4, 5, 6, 7], target = 5
Example output: 4

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>

using namespace std;

int binarySearch(vector<int> arr, int target) {
    int left = 0;
    int right = arr.size() - 1;
    int mid;

    while (left <= right) {
        mid = (left + right) / 2;
        if (arr[mid] == target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1;
}

int main() {
    vector<int> arr = {1, 2, 3, 4, 5, 6, 7};
    int target = 5;

    cout << binarySearch(arr, target) << endl;

    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly implements a binary search algorithm to find the index of a given target value in a sorted array. The solution is complete and correctly handles the case where the target value is not present in the array.

Evaluated at: 2022-11-25 06:16:15