binary_search/vanilla_binary_search

Python Solution - ✅ Pass

def binary_search(arr: list[int], target: int) -> int:
    left, right = 0, len(arr) - 1
    # <= because left and right could point to the same element, < would miss it
    while left <= right:
        # double slash for integer division in python 3,
        # we don't have to worry about integer `left + right` overflow
        # since python integers can be arbitrarily large
        mid = (left + right) // 2
        # found target, return its index
        if arr[mid] == target:
            return mid
        # middle less than target, discard left half by making left search boundary `mid + 1`
        if arr[mid] < target:
            left = mid + 1
        # middle greater than target, discard right half by making right search boundary `mid - 1`
        else:
            right = mid - 1
    return -1  # if we get here we didn't hit above return so we didn't find target

if __name__ == "__main__":
    arr = [int(x) for x in input().split()]
    target = int(input())
    res = binary_search(arr, target)
    print(res)

C++ Solution - ✅ Pass

#include <algorithm>
#include <iostream>
#include <iterator>
#include <limits>
#include <sstream>
#include <string>
#include <vector>

int binary_search(std::vector<int>& arr, int target) {
    // WRITE YOUR BRILLIANT CODE HERE
    int left = 0;
    int right = std::size(arr) - 1;
    int mid;
    while (left <= right) {
        mid = left + (right - left) / 2;
        if (arr.at(mid) == target) {
            return mid;
        }
        if (arr.at(mid) < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

template<typename T>
std::vector<T> get_words() {
    std::string line;
    std::getline(std::cin, line);
    std::istringstream ss{line};
    ss >> std::boolalpha;
    std::vector<T> v;
    std::copy(std::istream_iterator<T>{ss}, std::istream_iterator<T>{}, std::back_inserter(v));
    return v;
}

void ignore_line() {
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

int main() {
    std::vector<int> arr = get_words<int>();
    int target;
    std::cin >> target;
    ignore_line();
    int res = binary_search(arr, target);
    std::cout << res << '\n';
}

JavaScript Solution - ✅ Pass

"use strict";

function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;

    // <= because left and right could point to the same element, < would miss it
    while (left <= right) {
        const mid = left + Math.floor((right - left) / 2); // use `(right - left) / 2` to prevent `left + right` potential overflow
        if (arr[mid] === target) return mid; // found target, return its index
        if (arr[mid] < target) {
            // middle less than target, discard left half by making left search boundary `mid + 1`
            left = mid + 1;
        } else {
            // middle greater than target, discard right half by making right search boundary `mid - 1`
            right = mid - 1;
        }
    }
    // if we get here we didn't hit above return so we didn't find target
    return -1;
}

function splitWords(s) {
    return s === "" ? [] : s.split(" ");
}

function* main() {
    const arr = splitWords(yield).map((v) => parseInt(v));
    const target = parseInt(yield);
    const res = binarySearch(arr, target);
    console.log(res);
}

class EOFError extends Error { }
{
    const gen = main();
    const next = (line) => gen.next(line).done && process.exit();
    let buf = "";
    next();
    process.stdin.setEncoding("utf8");
    process.stdin.on("data", (data) => {
        const lines = (buf + data).split("\n");
        buf = lines.pop();
        lines.forEach(next);
    });
    process.stdin.on("end", () => {
        buf && next(buf);
        gen.throw(new EOFError());
    });
}