Binary Search

The problem is to find the index of a given target value in a sorted array of integers, using the binary search algorithm. If the target value is not present in the array, the function should return -1.

Problem

Given a sorted array of integers and a target value, find the index of the target value in the array. If the target value is not present in the array, return -1.
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;
    while (left <= right) {
        int mid = left + (right - left) / 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 complete and solves the problem. The candidate has used a binary search algorithm, which is a common and efficient approach to solving this problem.

Evaluated at: 2022-12-07 14:15:34