Sitemap

Binary search

2 min readSep 4, 2025

--

Press enter or click to view image in full size
Visualiztion of binary search

What is binary search?

Binary search is a searching algorithm, which searches the target element in a sorted array. It is one of the basic searching algorithm in computer science field.

How does it work?

The algorithm is very simple, it uses two pointers to adjust the searching space of the given array. The first pointer is on the first element of the array, the second pointer is on the last element of the array. Using these two pointers, we find out the mid-element. The key idea is to use the mid-element in the searching space and compare it with the target element.

Get Pabitra’s stories in your inbox

Join Medium for free to get updates from this writer.

Now if,

  1. arr[mid]>target, then it means that target is on the left of the mid-element. We have to reduce the searching space from the right side of the array, bringing the right pointer on the left side of the mid-element.
  2. arr[mid]<target, then it means that target is on the right of mid-element, and we have reduced the space from the left side, bringing the left pointer on mid+1 element.
  3. And, if the mid-element is the target element then we return the index, or if it's not found, we return -1.
  4. This loops continues to happen until we found the element or left pointer crosses the right pointer.

Code

class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int low=0, high=n-1;

while (low<=high){

int mid = low+(high-low)/2;

if (nums[mid]>target) high = mid-1;
else if (nums[mid]<target) low = mid+1;
else return mid;

}

return -1;
}
};

TC & SC

The time complexity of the algorithm is O(logn), where n is the size of the input array, logn because it divides the searching space in half at every iteration.

No extra space is used to solve the program, hence the space complexity is O(1) or constant.

--

--

Pabitra
Pabitra

Written by Pabitra

Ordinary person, supercharged with coffee.