编辑代码

function binarySearch(arr, k) {
    let low = 0;
    let high = arr.length - 1;

    while (low <= high) {
        const mid = Math.floor((low + high) / 2);

        if (arr[mid] === k) {
            return true; // 元素找到
        } else if (arr[mid] < k) {
            low = mid + 1; // 元素在右半部分
        } else {
            high = mid - 1; // 元素在左半部分
        }
    }

    return false; // 元素不存在
}

const sortedArray = [6, 17, 25, 34, 52, 63, 85];
const elementToFind = 6;

const isElementFound = binarySearch(sortedArray, elementToFind);

if (isElementFound) {
    console.log(`元素 ${elementToFind} 存在于数组中。`);
} else {
    console.log(`元素 ${elementToFind} 不存在于数组中。`);
}