JavaScript 二分查找算法实现
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;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; }
// 测试 const arr = [1, 3, 5, 7, 9]; console.log(binarySearch(arr, 3)); // 1 console.log(binarySearch(arr, 6)); // -1
原文地址: https://www.cveoy.top/t/topic/mU4u 著作权归作者所有。请勿转载和采集!