编辑代码

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

    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] === target) {
            return mid;
        }
        if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }

    return -1; // 如果未找到目标元素
}


const testArray1 = [1, 3, 5, 7, 9, 11, 13];
const target1 = 7;
console.log("Test 1:", binarySearch(testArray1, target1)); 

const testArray2 = [2, 4, 6, 8, 10, 12];
const target2 = 5;
console.log("Test 2:", binarySearch(testArray2, target2)); 

const testArray3 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const target3 = 10;
console.log("Test 3:", binarySearch(testArray3, target3));