algorithms

Algorithms Handbook

View on GitHub

Binary Search

Also known as logarithmic search or half-interval search.

Overview

Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare to the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.

Complexity

BS runs in $O(\log n)$ time, making $n$ comparisons, where $n$ is the number of elements in the array. BS is a dichotomous divide and conquer algorithm.

Use cases

There are specialized data structures designed for fast searching, such as hash tables, that can be searched more efficiently than binary search.

However, binary search can be used to solve a wider range of problems, such as:

Variations