Binary search in a sorted array

The problem is to find the index of a given target value in a sorted array of integers, or return -1 if the target value is not present in the array.

Problem

Given a sorted array of integers and a target value, write a function that returns the index of the target value if it exists in the array, or -1 if it does not.
Example input: [1, 2, 3, 4, 5], 3
Example output: 2

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};
    int target = 3;

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

    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is a complete and working solution to the problem. The candidate has used a binary search algorithm, which is an efficient way to search for a value in a sorted array.

Evaluated at: 2022-11-24 18:15:35