Binary Search: Determine if Target Value Exists in Sorted Array

This problem asks the reader to determine whether a target value exists in a sorted array of integers. An example input and output are given.

Problem

Given a sorted array of integers and a target value, determine if the target value exists in the array.
Example input:
nums = [1, 2, 3, 4, 5]
target = 3
Example output:
True

Solution

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

using namespace std;

bool binarySearch(vector<int> nums, int target) {
    int left = 0;
    int right = nums.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (nums[mid] == target) {
            return true;
        } else if (nums[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return false;
}

int main() {
    vector<int> nums = {1, 2, 3, 4, 5};
    int target = 3;
    cout << binarySearch(nums, target) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly implements a binary search algorithm to solve the problem. The code is well organized and easy to read. The candidate demonstrates a good understanding of the algorithm and its implementation.

Evaluated at: 2022-11-22 04:15:50