This is an old version, saved 5 Dec 2026, 07:26 by TechWritereditor. See the current version.

Binary search algorithm

The binary search algorithm is a method for finding a value in a sorted array by repeatedly halving the search interval.[1] It is one of the simplest examples of the divide-and-conquer approach and is used inside other techniques such as binary insertion sort and suffix arrays.[1]

Contents
  1. How it works
  2. History
  3. See also
  4. References

How it works

The search begins with the whole list and compares the target with the middle item. If they match, the search ends; if the target is smaller, the search continues in the lower half, otherwise in the upper half.[1][2] This repeats until the value is found or the remaining interval is empty, which means the value is not present.[1] The list must be sorted in advance, otherwise the result cannot be trusted.[2]

Because each step discards half of the remaining items, a search of n items needs at most about 1 + log2 n comparisons: roughly 20 for a million items and 30 for a billion. Doubling the size of the list adds only one comparison.[2] A linear search, which checks items one by one, has a cost that grows in direct proportion to the size of the list.[2] On a linked list, however, binary search still makes only a logarithmic number of comparisons but must step through the list, so it is no faster than a linear search.[1]

History

John Mauchly made the first recorded mention of binary search in 1946, during the Moore School Lectures on electronic computing.[3] Early versions worked only on lists whose length was a power of two; in 1960 Derrick Henry Lehmer published a version without that restriction.[3] Writing correct code for the method proved surprisingly difficult: Jon Bentley's Programming Pearls noted that although the first binary search was published in 1946, the first version that worked for all list sizes did not appear until 1962.[4]

In 2006 Joshua Bloch of Google reported that the version in the Java (programming language) library, and many others, contained a bug that had gone unnoticed for about nine years. Calculating the midpoint as (low + high) / 2 can overflow when the array has around a billion or more elements, producing a negative index.[4] Safer forms such as low + (high − low) / 2 avoid the problem.[1][4]

See also

References

  1. ^ binary search – Dictionary of Algorithms and Data Structures. National Institute of Standards and Technology. 2022-04-21. xlinux.nist.gov
  2. ^ Binary Search (15-110 lecture, Unit 5). Carnegie Mellon University. cs.cmu.edu
  3. ^ Data Structures History (CSC 162 lecture). University of Rochester. cs.rochester.edu
  4. ^ Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken. Google Research. 2006-06-02. research.google