2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
Binary Search is an efficient search algorithm that is suitable for quickly locating target elements in an ordered array. Compared with linear search, the time complexity of binary search is O(log n), which is more efficient. This article will introduce the principle, implementation and application of binary search algorithm in detail.
Binary search quickly locates the target element by continuously halving the search range. The basic steps are as follows:
Here is a JavaScript implementation of binary search:
/**
* 二分查找算法
* @param {number[]} arr - 有序数组
* @param {number} target - 目标元素
* @return {number} - 目标元素的索引,未找到返回 -1
*/
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, 11, 13];
const target = 7;
const index = binarySearch(arr, target);
console.log(index); // 输出: 3
/**
* 递归实现二分查找算法
* @param {number[]} arr - 有序数组
* @param {number} target - 目标元素
* @param {number} left - 左索引
* @param {number} right - 右索引
* @return {number} - 目标元素的索引,未找到返回 -1
*/
function binarySearchRecursive(arr, target, left = 0, right = arr.length - 1) {
if (left > right) {
return -1; // 未找到目标元素
}
const mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // 找到目标元素
} else if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, right); // 查找右半部分
} else {
return binarySearchRecursive(arr, target, left, mid - 1); // 查找左半部分
}
}
// 示例
const indexRecursive = binarySearchRecursive(arr, target);
console.log(indexRecursive); // 输出: 3
Binary search is an efficient search algorithm that can quickly locate the target element in an ordered array by continuously halving the search range. Understanding and mastering the binary search algorithm is of great significance for solving many practical problems and optimizing program performance. I hope this article will help you understand and apply binary search.