# Binary search

**Binary search** is an algorithm which quickly locates an entry with a given value in a sorted array, or determines that no such entry exists, by taking advantage of the sorted precondition of the array. Binary search is much faster than linear search, which simply checks each entry of the array in order, although linear search works when the array is not sorted.

Without loss of generality, assume that the array is sorted in ascending order. Initially, the range in consideration is the entire array. Consider the midpoint of the valid array indices, usually taken to be the floor of the arithmetic mean of the two endpoints. If the entry at the midpoint has the desired value, then the midpoint is the result and the method terminates. If the value of the entry at the midpoint is greater than the desired value, then it and all entries with greater indices are eliminated. If the value of the entry at the midpoint is less than the desired value, then it and all entries with lesser indices are eliminated.

To find the value in an array with indices through , the binary search algorithm can be summarized by the following cases:

- If at any point , then is not in .

Otherwise, let .

- If , return as the result.
- If , search again, replacing with .
- If , search again, replacing with .