Binary Search

A logarithmic-time search algorithm for sorted arrays.

Time Complexity

O(log n)

Very Fast

Space Complexity

O(1)

Immediate

In-Place

Yes

Yes

Stability

Yes

Yes

Difficulty

Easy

★★☆☆☆

Description

Binary Search is an efficient algorithm for finding an element in a sorted array.

It works by repeatedly dividing the search interval in half:

  1. Compare the target with the middle element
  2. If equal, return the index
  3. If less, repeat on the left half
  4. If greater, repeat on the right half

It is extremely fast with a time complexity of O(log n) but only applicable to sorted collections.

Computational Complexity

O(1)
Best
O(log n)
Average
O(log n)
Worst
O(1)
Spatial

Implementation