Binary search is an efficient algorithm for finding an item from an ordered list of items. It works by repeatedly dividing in half the portion of the list, until narrowing down the possible locations to just one. The time complexity reduces from O(n) to O(logn).

binary search

Table of Content

How does binary search work?

Binary search repeatedly compares the key with the item in the middle of a sorted array, until narrows down to just one.

What is the time complexity of binary search?

Binary search skips half of the comparisons after each iteration. The search time reduces from O(n) to O(logn). Binary search is fast.


Iterative solution

Java

Javascript

Python

Doodle

binary search doodle


Recursive solution

Java

Javascript

Python


Free download

Download Java, JavaScript and Python code
Algorithm types and algorithm examples