Binary Search Algorithm

Maryann Gitonga
2 min readSep 4, 2023

--

How it works

You are searching for an item in a really long list. You start right in the middle because, well, it’s a good place to begin. If the item you are looking for is not in the middle, you instantly know whether it should be on the left or the right. So, you chop your list in half, discarding the other half that is now irrelevant, and keep going. You repeat this until you find what you’re looking for or run out of list of items to search through. That’s binary search.

For this algorithm to work, you will need to have your list of items sorted in some order. This way, you can make those smart comparisons at every step, figuring out exactly which direction to move and which half to ditch.

Illustration of Binary Search

Benefits

  1. Efficient Time Complexity: It has a time complexity of O(log n) which is incredibly efficient for large datasets compared to linear search.
  2. Smart Space Reduction: It systematically eliminates half of the remaining search space with each comparison.

Real-life application

In search engines like Google, binary search is used in the indexing algorithms to quickly locate web pages or documents that match a search query. Binary search helps find the most relevant results efficiently, which are often sorted by relevance.

Simple Code Illustration

Where next?

--

--

Maryann Gitonga

A Software Engineer who loves trying out different tooling & engineering concepts in Back-end Engineering & DevOps. An explorer in the ML world too!