Binary Search
Introduction
Binary search is a searching algorithm, used to search for an element in an array. It follows a unique approach which reduces the time complexity as compared to linear search. However, to use binary search, the array must be sorted.
Video Explanation

Binary Search Visualization
Loading visualizer...
Implementation
Let us see how to implement binary search in Java:
//let element to be found=target
int low=0;
int high=n-1; //where n is the length of the sorted array
int mid; //represents the mid index of the array
int flag=0; //element not yet found
while(low<=high) {
mid=(low + high)/2;
if(arr[mid]==target) {
flag=1; //element found
System.out.println("Target found!");
break;
}
else if(arr[mid]<target) {
// which means target is to the right of mid element
low=mid+1;
}
else {
//target is to the left of mid element
high=mid-1;
}
}
if(flag==0) {
System.out.println("Target not found!");
}
Implementation
Let us see how to implement binary search in javascript:
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
let flag = false; // element not yet found
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
flag = true; // element found
console.log("Target found!");
break;
} else if (arr[mid] < target) {
// target is to the right of mid element
low = mid + 1;
} else {
// target is to the left of mid element
high = mid - 1;
}
}
if (!flag) {
console.log("Target not found!");
}
}
// Example usage
let arr = [1, 3, 5, 7, 9, 11];
let target = 7;
binarySearch(arr, target);
In this algorithm, the searching interval of the array is divided into half at every iteration until the target is found. This results in lesser comparisions and decreases the time required.
Dry Run Examples
We will walk through two detailed dry run examples using the following sample sorted array:
Indices: 0 1 2 3 4 5 6 7 8 9
Array: [ 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 ]
Example 1: Target Element Exists (Target = 23)
We search for the target value 23 in the array.
Step-by-Step Execution
Iteration 1
- Search Space: Index
0to9(entire array). - Pointers:
low = 0,high = 9 - Midpoint Calculation:
- Middle Element:
arr[mid] = arr[4] = 16 - Visual Representation:
Indices: 0 1 2 3 [4] 5 6 7 8 9Array: [ 2, 5, 8, 12, 16, 23, 38, 56, 72, 91 ]^ ^ ^low mid high
- Comparison & Decision:
arr[mid]() is less than target ().- Since the array is sorted, the target must reside in the right half of the current search space.
- We discard the left half by updating:
low = mid + 1 = 5.
Iteration 2
- Search Space: Index
5to9. - Pointers:
low = 5,high = 9 - Midpoint Calculation:
- Middle Element:
arr[mid] = arr[7] = 56 - Visual Representation:
Indices: 0 1 2 3 4 5 6 [7] 8 9Array: [ - - - - - 23, 38, 56, 72, 91 ]^ ^ ^low mid high
- Comparison & Decision:
arr[mid]() is greater than target ().- The target must reside in the left half of the remaining search space.
- We discard the right half by updating:
high = mid - 1 = 6.