Answers for "binary search .co"

0

Binary Search

const numbers = [1, 2, 3,4,5,6,7,8,9,10];

function binarySearch(sortedArray, key){
    let start = 0;
    let end = sortedArray.length - 1;

    while (start <= end) {
        let middle = Math.floor((start + end) / 2);
        console.log(middle)
        if (sortedArray[middle] === key) {
            // found the key
            return middle;
        } else if (sortedArray[middle] < key) {
            // continue searching to the right
            start = middle + 1;
        } else {
            // search searching to the left
            
            end = middle - 1;
        }
    }
	// key wasn't found
    return -1;
}

console.log(binarySearch(numbers,4))
Posted by: Guest on February-16-2022

Python Answers by Framework

Browse Popular Code Answers by Language