Binary search is a highly efficient algorithm used to search for a specific element within a sorted array. Its effectiveness stems from its divide-and-conquer strategy, repeatedly halving the search space until the target element is found or determined to be absent.
Initialization: Start with a sorted array and a target element you wish to find. Initialize two pointers, left
and right
, to the beginning and end of the array respectively.
Iteration: While left
is less than or equal to right
:
mid
as the average of left
and right
.Compare the element at mid
with the target element.
mid
, update right
to mid - 1
.mid
, update left
to mid + 1
.Termination: If the loop terminates without finding the target element, it means the target element is not present in the array.
function binarySearch(array, target) {
let left = 0;
let right = array.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (array[mid] === target) {
return mid; // Element found
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Element not found
}
Consider the following sorted array: [2, 5, 7, 8, 11, 12]
. Let's search for the target element 11
.
left = 0
, right = 5
, mid = 2
.array[mid] = 7 < target
.left = mid + 1 = 3
.left = 3
, right = 5
, mid = 4
.array[mid] = 11 = target
.mid = 4
is returned.Binary search has a time complexity of O(log n), where n is the number of elements in the array. This logarithmic complexity arises from the halving of the search space with each iteration.
Binary search finds widespread use in various applications: