Binary Search Algorithm - Wikipedia
Binary Search Algorithm - Wikipedia
Contents
Algorithm
Procedure
Alternative procedure
Duplicate elements
Procedure for finding the leftmost element
Procedure for finding the rightmost element
Approximate matches
Performance
Space complexity
Derivation of average case
Successful searches
Unsuccessful searches
Performance of alternative procedure
Running time and cache use
Binary search versus other schemes
Linear search
Trees
Hashing
Set membership algorithms
Other data structures
Variations
Uniform binary search
Exponential search
https://en.wikipedia.org/wiki/Binary_search_algorithm 1/17
24.08.2021 Binary search algorithm - Wikipedia
Interpolation search
Fractional cascading
Generalization to graphs
Noisy binary search
Quantum binary search
History
Implementation issues
Library support
See also
Notes and references
Notes
Citations
Sources
External links
Algorithm
Binary search works on sorted arrays. Binary search begins by comparing an element in the middle of the array
with the target value. If the target value matches the element, its position in the array is returned. If the target value
is less than the element, the search continues in the lower half of the array. If the target value is greater than the
element, the search continues in the upper half of the array. By doing this, the algorithm eliminates the half in
which the target value cannot lie in each iteration.[7]
Procedure
1. Set to and to .
2. If , the search terminates as unsuccessful.
3. Set (the position of the middle element) to the floor of , which is the greatest integer less than or
equal to .
This iterative procedure keeps track of the search boundaries with the two variables and . The procedure may
be expressed in pseudocode as follows, where the variable names and types remain the same as above, floor is the
floor function, and unsuccessful refers to a specific value that conveys the failure of the search.[7]
function binary_search(A, n, T) is
L := 0
R := n − 1
while L ≤ R do
m := floor((L + R) / 2)
L := m + 1
R := m − 1
else:
return m
return unsuccessful
Alternatively, the algorithm may take the ceiling of . This may change the result if the target value appears
more than once in the array.
https://en.wikipedia.org/wiki/Binary_search_algorithm 2/17
24.08.2021 Binary search algorithm - Wikipedia
Alternative procedure
In the above procedure, the algorithm checks whether the middle element ( ) is equal to the target ( ) in every
iteration. Some implementations leave out this check during each iteration. The algorithm would perform this
check only when one element is left (when ). This results in a faster comparison loop, as one comparison is
eliminated per iteration. However, it requires one more iteration on average.[8]
Hermann Bottenbruch published the first implementation to leave out this check in 1962.[8][9]
1. Set to and to .
2. While ,
1. Set (the position of the middle element) to the ceiling of , which is the least integer greater than or
equal to .
2. If , set to .
3. Else, ; set to .
3. Now , the search is done. If , return . Otherwise, the search terminates as unsuccessful.
Where ceil is the ceiling function, the pseudocode for this version is:
function binary_search_alternative(A, n, T) is
L := 0
R := n − 1
while L != R do
m := ceil((L + R) / 2)
R := m − 1
else:
L := m
if A[L] = T then
return L
return unsuccessful
Duplicate elements
The procedure may return any index whose element is equal to the target value, even if there are duplicate
elements in the array. For example, if the array to be searched was and the target was , then it
would be correct for the algorithm to either return the 4th (index 3) or 5th (index 4) element. The regular
procedure would return the 4th element (index 3) in this case. It does not always return the first duplicate
(consider which still returns the 4th element). However, it is sometimes necessary to find the
leftmost element or the rightmost element for a target value that is duplicated in the array. In the above example,
the 4th element is the leftmost element of the value 4, while the 5th element is the rightmost element of the value 4.
The alternative procedure above will always return the index of the rightmost element if such an element exists.[9]
1. Set to and to .
2. While ,
1. Set (the position of the middle element) to the floor of , which is the greatest integer less than or
equal to .
2. If , set to .
3. Else, ; set to .
3. Return .
If and , then is the leftmost element that equals . Even if is not in the array, is the rank of
in the array, or the number of elements in the array that are less than .
https://en.wikipedia.org/wiki/Binary_search_algorithm 3/17
24.08.2021 Binary search algorithm - Wikipedia
Where floor is the floor function, the pseudocode for this version is:
L := 0
R := n
while L < R:
m := floor((L + R) / 2)
if A[m] < T:
L := m + 1
else:
R := m
return L
1. Set to and to .
2. While ,
1. Set (the position of the middle element) to the floor of , which is the greatest integer less than or
equal to .
2. If , set to .
3. Else, ; set to .
3. Return .
If and , then is the rightmost element that equals . Even if is not in the array, is
the number of elements in the array that are greater than .
Where floor is the floor function, the pseudocode for this version is:
L := 0
R := n
while L < R:
m := floor((L + R) / 2)
if A[m] > T:
R := m
else:
L := m + 1
return R - 1
Approximate matches
https://en.wikipedia.org/wiki/Binary_search_algorithm 4/17
24.08.2021 Binary search algorithm - Wikipedia
Range queries are also straightforward.[12] Once the ranks of the two values are known, the number of
elements greater than or equal to the first value and less than the second is the difference of the two ranks.
This count can be adjusted up or down by one according to whether the endpoints of the range should be
considered to be part of the range and whether the array contains entries matching those endpoints.[13]
Performance
In terms of the number of comparisons, the performance of binary search can be
analyzed by viewing the run of the procedure on a binary tree. The root node of the
tree is the middle element of the array. The middle element of the lower half is the left
child node of the root, and the middle element of the upper half is the right child node
of the root. The rest of the tree is built in a similar fashion. Starting from the root
node, the left or right subtrees are traversed depending on whether the target value is
less or more than the node under consideration.[6][14]
In the best case, where the target value is the middle element of the array, its position is returned after one
iteration.[16]
In terms of iterations, no search algorithm that works only by comparing elements can exhibit better average and
worst-case performance than binary search. The comparison tree representing binary search has the fewest levels
possible as every level above the lowest level of the tree is filled completely.[b] Otherwise, the search algorithm can
eliminate few elements in an iteration, increasing the number of iterations required in the average and worst case.
This is the case for other search algorithms based on comparisons, as while they may work faster on some target
values, the average performance over all elements is worse than binary search. By dividing the array in half, binary
search ensures that the size of both subarrays are as similar as possible.[14]
Space complexity
Binary search requires three pointers to elements, which may be array indices or pointers to memory locations,
regardless of the size of the array. Therefore, the space complexity of binary search is in the word RAM model
of computation.
The average number of iterations performed by binary search depends on the probability of each element being
searched. The average case is different for successful searches and unsuccessful searches. It will be assumed that
each element is equally likely to be searched for successful searches. For unsuccessful searches, it will be assumed
that the intervals between and outside elements are equally likely to be searched. The average case for successful
searches is the number of iterations required to search every element exactly once, divided by , the number of
elements. The average case for unsuccessful searches is the number of iterations required to search an element
within every interval exactly once, divided by the intervals.[14]
Successful searches
In the binary tree representation, a successful search can be represented by a path from the root to the target node,
called an internal path. The length of a path is the number of edges (connections between nodes) that the path
passes through. The number of iterations performed by a search, given that the corresponding path has length , is
counting the initial iteration. The internal path length is the sum of the lengths of all unique internal paths.
Since there is only one path from the root to any single node, each internal path represents a search for a specific
element. If there are elements, which is a positive integer, and the internal path length is , then the average
number of iterations for a successful search , with the one iteration added to count the initial
iteration.[14]
Since binary search is the optimal algorithm for searching with comparisons, this problem is reduced to calculating
the minimum internal path length of all binary trees with nodes, which is equal to:[17]
For example, in a 7-element array, the root requires one iteration, the two elements below the root require two
iterations, and the four elements below require three iterations. In this case, the internal path length is:[17]
The average number of iterations would be based on the equation for the average case. The sum for
can be simplified to:[14]
For integer , this is equivalent to the equation for the average case on a successful search specified above.
Unsuccessful searches
Unsuccessful searches can be represented by augmenting the tree with external nodes, which forms an extended
binary tree. If an internal node, or a node present in the tree, has fewer than two child nodes, then additional child
nodes, called external nodes, are added so that each internal node has two children. By doing so, an unsuccessful
search can be represented as a path to an external node, whose parent is the single element that remains during the
last iteration. An external path is a path from the root to an external node. The external path length is the sum of
the lengths of all unique external paths. If there are elements, which is a positive integer, and the external path
length is , then the average number of iterations for an unsuccessful search , with the one
iteration added to count the initial iteration. The external path length is divided by instead of because
there are external paths, representing the intervals between and outside the elements of the array.[14]
https://en.wikipedia.org/wiki/Binary_search_algorithm 6/17
24.08.2021 Binary search algorithm - Wikipedia
This problem can similarly be reduced to determining the minimum external path length of all binary trees with
nodes. For all binary trees, the external path length is equal to the internal path length plus .[17] Substituting the
equation for :[14]
Substituting the equation for into the equation for , the average case for unsuccessful searches can be
determined:[14]
Each iteration of the binary search procedure defined above makes one or two comparisons, checking if the middle
element is equal to the target in each iteration. Assuming that each element is equally likely to be searched, each
iteration makes 1.5 comparisons on average. A variation of the algorithm checks whether the middle element is
equal to the target at the end of the search. On average, this eliminates half a comparison from each iteration. This
slightly cuts the time taken per iteration on most computers. However, it guarantees that the search takes the
maximum number of iterations, on average adding one iteration to the search. Because the comparison loop is
performed only times in the worst case, the slight increase in efficiency per iteration does not
compensate for the extra iteration for all but very large .[c][18][19]
In analyzing the performance of binary search, another consideration is the time required to compare two
elements. For integers and strings, the time required increases linearly as the encoding length (usually the number
of bits) of the elements increase. For example, comparing a pair of 64-bit unsigned integers would require
comparing up to double the bits as comparing a pair of 32-bit unsigned integers. The worst case is achieved when
the integers are equal. This can be significant when the encoding lengths of the elements are large, such as with
large integer types or long strings, which makes comparing elements expensive. Furthermore, comparing floating-
point values (the most common digital representation of real numbers) is often more expensive than comparing
integers or short strings.
On most computer architectures, the processor has a hardware cache separate from RAM. Since they are located
within the processor itself, caches are much faster to access but usually store much less data than RAM. Therefore,
most processors store memory locations that have been accessed recently, along with memory locations close to it.
For example, when an array element is accessed, the element itself may be stored along with the elements that are
stored close to it in RAM, making it faster to sequentially access array elements that are close in index to each other
(locality of reference). On a sorted array, binary search can jump to distant memory locations if the array is large,
unlike algorithms (such as linear search and linear probing in hash tables) which access elements in sequence. This
adds slightly to the running time of binary search for large arrays on most systems.[20]
Linear search
https://en.wikipedia.org/wiki/Binary_search_algorithm 7/17
24.08.2021 Binary search algorithm - Wikipedia
Linear search is a simple search algorithm that checks every record until it finds the target value. Linear search can
be done on a linked list, which allows for faster insertion and deletion than an array. Binary search is faster than
linear search for sorted arrays except if the array is short, although the array needs to be sorted beforehand.[d][24]
All sorting algorithms based on comparing elements, such as quicksort and merge sort, require at least
comparisons in the worst case.[25] Unlike linear search, binary search can be used for efficient approximate
matching. There are operations such as finding the smallest and largest element that can be done efficiently on a
sorted array but not on an unsorted array.[26]
Trees
A binary search tree is a binary tree data structure that works based on the
principle of binary search. The records of the tree are arranged in sorted order,
and each record in the tree can be searched using an algorithm similar to
binary search, taking on average logarithmic time. Insertion and deletion also
require on average logarithmic time in binary search trees. This can be faster
than the linear time insertion and deletion of sorted arrays, and binary trees
retain the ability to perform all the operations possible on a sorted array,
including range and approximate queries.[22][27]
However, binary search is usually more efficient for searching as binary search
trees will most likely be imperfectly balanced, resulting in slightly worse Binary search trees are searched
performance than binary search. This even applies to balanced binary search using an algorithm similar to binary
trees, binary search trees that balance their own nodes, because they rarely search.
produce the tree with the fewest possible levels. Except for balanced binary
search trees, the tree may be severely imbalanced with few internal nodes with
two children, resulting in the average and worst-case search time approaching comparisons.[e] Binary search
trees take more space than sorted arrays.[29]
Binary search trees lend themselves to fast searching in external memory stored in hard disks, as binary search
trees can be efficiently structured in filesystems. The B-tree generalizes this method of tree organization. B-trees
are frequently used to organize long-term storage such as databases and filesystems.[30][31]
Hashing
For implementing associative arrays, hash tables, a data structure that maps keys to records using a hash function,
are generally faster than binary search on a sorted array of records.[32] Most hash table implementations require
only amortized constant time on average.[f][34] However, hashing is not useful for approximate matches, such as
computing the next-smallest, next-largest, and nearest key, as the only information given on a failed search is that
the target is not present in any record.[35] Binary search is ideal for such matches, performing them in logarithmic
time. Binary search also supports approximate matches. Some operations, like finding the smallest and largest
element, can be done efficiently on sorted arrays but not on hash tables.[22]
A related problem to search is set membership. Any algorithm that does lookup, like binary search, can also be
used for set membership. There are other algorithms that are more specifically suited for set membership. A bit
array is the simplest, useful when the range of keys is limited. It compactly stores a collection of bits, with each bit
representing a single key within the range of keys. Bit arrays are very fast, requiring only time.[36] The Judy1
type of Judy array handles 64-bit keys efficiently. [37]
For approximate results, Bloom filters, another probabilistic data structure based on hashing, store a set of keys by
encoding the keys using a bit array and multiple hash functions. Bloom filters are much more space-efficient than
bit arrays in most cases and not much slower: with hash functions, membership queries require only time.
However, Bloom filters suffer from false positives. [g][h][39]
There exist data structures that may improve on binary search in some cases for both searching and other
operations available for sorted arrays. For example, searches, approximate matches, and the operations available to
sorted arrays can be performed more efficiently than binary search on specialized data structures such as van Emde
https://en.wikipedia.org/wiki/Binary_search_algorithm 8/17
24.08.2021 Binary search algorithm - Wikipedia
Boas trees, fusion trees, tries, and bit arrays. These specialized data structures are usually only faster because they
take advantage of the properties of keys with a certain attribute (usually keys that are small integers), and thus will
be time or space consuming for keys that lack that attribute.[22] As long as the keys can be ordered, these
operations can always be done at least efficiently on a sorted array regardless of the keys. Some structures, such as
Judy arrays, use a combination of approaches to mitigate this while retaining efficiency and the ability to perform
approximate matching.[37]
Variations
Uniform binary search stores, instead of the lower and upper bounds, the
difference in the index of the middle element from the current iteration to the
next iteration. A lookup table containing the differences is computed
beforehand. For example, if the array to be searched is
Uniform binary search stores the
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], the middle element ( ) would be 6. In this difference between the current and
case, the middle element of the left subarray ([1, 2, 3, 4, 5]) is 3 and the the two next possible middle
middle element of the right subarray ([7, 8, 9, 10, 11]) is 9. Uniform binary elements instead of specific bounds.
search would store the value of 3 as both indices differ from 6 by this same
amount.[40] To reduce the search space, the algorithm either adds or subtracts
this change from the index of the middle element. Uniform binary search may be faster on systems where it is
inefficient to calculate the midpoint, such as on decimal computers.[41]
Exponential search
Interpolation search
In practice, interpolation search is slower than binary search for small arrays, as interpolation search requires extra
computation. Its time complexity grows more slowly than binary search, but this only compensates for the extra
computation for large arrays.[43]
Fractional cascading
https://en.wikipedia.org/wiki/Binary_search_algorithm 9/17
24.08.2021 Binary search algorithm - Wikipedia
Fractional cascading is a
technique that speeds up binary
searches for the same element
in multiple sorted arrays.
Searching each array separately
requires time, where
is the number of arrays.
Fractional cascading reduces
this to by storing
specific information in each
array about each element and
In fractional cascading, each array has pointers to every second element of another array,
its position in the other so only one binary search has to be performed to search all the arrays.
arrays.[46][47]
Generalization to graphs
Binary search has been generalized to work on certain types of graphs, where the target value is stored in a vertex
instead of an array element. Binary search trees are one such generalization—when a vertex (node) in the tree is
queried, the algorithm either learns that the vertex is the target, or otherwise which subtree the target would be
located in. However, this can be further generalized as follows: given an undirected, positively weighted graph and
a target vertex, the algorithm learns upon querying a vertex that it is equal to the target, or it is given an incident
edge that is on the shortest path from the queried vertex to the target. The standard binary search algorithm is
simply the case where the graph is a path. Similarly, binary search trees are the case where the edges to the left or
right subtrees are given when the queried vertex is unequal to the target. For all undirected, positively weighted
graphs, there is an algorithm that finds the target vertex in queries in the worst case.[48]
is the binary
entropy function and is the probability that the procedure
yields the wrong position.[49][50][51] The noisy binary search In noisy binary search, there is a certain probability that
a comparison is incorrect.
problem can be considered as a case of the Rényi-Ulam
game,[52] a variant of Twenty Questions where the answers may
be wrong.[53]
Classical computers are bounded to the worst case of exactly iterations when performing binary
search. Quantum algorithms for binary search are still bounded to a proportion of queries (representing
iterations of the classical procedure), but the constant factor is less than one, providing for a lower time complexity
on quantum computers. Any exact quantum binary search procedure—that is, a procedure that always yields the
correct result—requires at least queries in the worst case, where is the natural
logarithm.[54] There is an exact quantum binary search procedure that runs in queries in
the worst case. [55] In comparison, Grover's algorithm is the optimal quantum algorithm for searching an unordered
list of elements, and it requires queries.[56]
https://en.wikipedia.org/wiki/Binary_search_algorithm 10/17
24.08.2021 Binary search algorithm - Wikipedia
History
The idea of sorting a list of items to allow for faster searching dates back to antiquity. The earliest known example
was the Inakibit-Anu tablet from Babylon dating back to c. 200 BCE. The tablet contained about 500 sexagesimal
numbers and their reciprocals sorted in lexicographical order, which made searching for a specific entry easier. In
addition, several lists of names that were sorted by their first letter were discovered on the Aegean Islands.
Catholicon, a Latin dictionary finished in 1286 CE, was the first work to describe rules for sorting words into
alphabetical order, as opposed to just the first few letters.[9]
In 1946, John Mauchly made the first mention of binary search as part of the Moore School Lectures, a seminal and
foundational college course in computing.[9] In 1957, William Wesley Peterson published the first method for
interpolation search.[9][57] Every published binary search algorithm worked only for arrays whose length is one less
than a power of two[i] until 1960, when Derrick Henry Lehmer published a binary search algorithm that worked on
all arrays.[59] In 1962, Hermann Bottenbruch presented an ALGOL 60 implementation of binary search that placed
the comparison for equality at the end, increasing the average number of iterations by one, but reducing to one the
number of comparisons per iteration.[8] The uniform binary search was developed by A. K. Chandra of Stanford
University in 1971.[9] In 1986, Bernard Chazelle and Leonidas J. Guibas introduced fractional cascading as a
method to solve numerous search problems in computational geometry.[46][60][61]
Implementation issues
Although the basic idea of binary search is comparatively straightforward, the details can be
surprisingly tricky
— Donald Knuth[2]
When Jon Bentley assigned binary search as a problem in a course for professional programmers, he found that
ninety percent failed to provide a correct solution after several hours of working on it, mainly because the incorrect
implementations failed to run or returned a wrong answer in rare edge cases.[62] A study published in 1988 shows
that accurate code for it is only found in five out of twenty textbooks.[63] Furthermore, Bentley's own
implementation of binary search, published in his 1986 book Programming Pearls, contained an overflow error
that remained undetected for over twenty years. The Java programming language library implementation of binary
search had the same overflow bug for more than nine years.[64]
In a practical implementation, the variables used to represent the indices will often be of fixed size (integers), and
this can result in an arithmetic overflow for very large arrays. If the midpoint of the span is calculated as ,
then the value of may exceed the range of integers of the data type used to store the midpoint, even if and
are within the range. If and are nonnegative, this can be avoided by calculating the midpoint as
.[65]
An infinite loop may occur if the exit conditions for the loop are not defined correctly. Once exceeds , the
search has failed and must convey the failure of the search. In addition, the loop must be exited when the target
element is found, or in the case of an implementation where this check is moved to the end, checks for whether the
search was successful or failed at the end must be in place. Bentley found that most of the programmers who
incorrectly implemented binary search made an error in defining the exit conditions.[8][66]
Library support
Many languages' standard libraries include binary search routines:
C provides the function bsearch() in its standard library, which is typically implemented via binary search,
although the official standard does not require it so.[67]
C++'s Standard Template Library provides the functions binary_search(), lower_bound(), upper_bound()
and equal_range().[68]
D's standard library Phobos, in std.range module provides a type SortedRange (returned by sort() and
assumeSorted() functions) with methods contains(), equaleRange(), lowerBound() and trisect(), that
use binary search techniques by default for ranges that offer random access.[69]
https://en.wikipedia.org/wiki/Binary_search_algorithm 11/17
24.08.2021 Binary search algorithm - Wikipedia
COBOL provides the SEARCH ALL verb for performing binary searches on COBOL ordered tables.[70]
Go's sort standard library package contains the functions Search, SearchInts, SearchFloat64s, and
SearchStrings, which implement general binary search, as well as specific implementations for searching
slices of integers, floating-point numbers, and strings, respectively.[71]
Java offers a set of overloaded binarySearch() static methods in the classes Arrays (https://docs.oracl
e.com/javase/10/docs/api/java/util/Arrays.html) and Collections (https://docs.oracle.com/j
avase/10/docs/api/java/util/Collections.html) in the standard java.util package for performing
binary searches on Java arrays and on Lists, respectively.[72][73]
Microsoft's .NET Framework 2.0 offers static generic versions of the binary search algorithm in its collection
base classes. An example would be System.Array's method BinarySearch<T>(T[] array, T value).[74]
For Objective-C, the Cocoa framework provides the NSArray -
indexOfObject:inSortedRange:options:usingComparator: (https://developer.apple.com/librar
y/mac/documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple
_ref/occ/instm/NSArray/indexOfObject:inSortedRange:options:usingComparator:) method in Mac
OS X 10.6+.[75] Apple's Core Foundation C framework also contains a CFArrayBSearchValues() (https://
developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFArrayRef/Referen
ce/reference.html#//apple_ref/c/func/CFArrayBSearchValues) function.[76]
Python provides the bisect module.[77]
Ruby's Array class includes a bsearch method with built-in approximate matching.[78]
See also
Bisection method – Algorithm for finding a zero of a function – the same idea used to solve equations in the
real numbers
Multiplicative binary search – Binary search variation with simplified midpoint calculation
Notes
a. The is Big O notation, and is the logarithm. In Big O notation, the base of the logarithm does not matter
since every logarithm of a given base is a constant factor of another logarithm of another base. That is,
, where is a constant.
b. Any search algorithm based solely on comparisons can be represented using a binary comparison tree. An
internal path is any path from the root to an existing node. Let be the internal path length, the sum of the
lengths of all internal paths. If each element is equally likely to be searched, the average case is or
simply one plus the average of all the internal path lengths of the tree. This is because internal paths represent
the elements that the search algorithm compares to the target. The lengths of these internal paths represent
the number of iterations after the root node. Adding the average of these lengths to the one iteration at the root
yields the average case. Therefore, to minimize the average number of comparisons, the internal path length
must be minimized. It turns out that the tree for binary search minimizes the internal path length. Knuth 1998
proved that the external path length (the path length over all nodes where both children are present for each
already-existing node) is minimized when the external nodes (the nodes with no children) lie within two
consecutive levels of the tree. This also applies to internal paths as internal path length is linearly related to
external path length . For any tree of nodes, . When each subtree has a similar number of
nodes, or equivalently the array is divided into halves in each iteration, the external nodes as well as their
interior parent nodes lie within two levels. It follows that binary search minimizes the number of average
comparisons as its comparison tree has the lowest possible internal path length.[14]
c. Knuth 1998 showed on his MIX computer model, which Knuth designed as a representation of an ordinary
computer, that the average running time of this variation for a successful search is units of
https://en.wikipedia.org/wiki/Binary_search_algorithm 12/17
24.08.2021 Binary search algorithm - Wikipedia
time compared to units for regular binary search. The time complexity for this variation grows
slightly more slowly, but at the cost of higher initial complexity. [18]
d. Knuth 1998 performed a formal time performance analysis of both of these search algorithms. On Knuth's MIX
computer, which Knuth designed as a representation of an ordinary computer, binary search takes on average
units of time for a successful search, while linear search with a sentinel node at the end of the list
takes units. Linear search has lower initial complexity because it requires minimal
computation, but it quickly outgrows binary search in complexity. On the MIX computer, binary search only
outperforms linear search with a sentinel if .[14][23]
e. Inserting the values in sorted order or in an alternating lowest-highest key pattern will result in a binary search
tree that maximizes the average and worst-case search time.[28]
f. It is possible to search some hash table implementations in guaranteed constant time.[33]
g. This is because simply setting all of the bits which the hash functions point to for a specific key can affect
queries for other keys which have a common hash location for one or more of the functions.[38]
h. There exist improvements of the Bloom filter which improve on its complexity or support deletion; for example,
the cuckoo filter exploits cuckoo hashing to gain these advantages.[38]
i. That is, arrays of length 1, 3, 7, 15, 31 ...[58]
Citations
1. Williams, Jr., Louis F. (22 April 1976). A modification to the half-interval search (binary search) method (https://d
l.acm.org/citation.cfm?doid=503561.503582). Proceedings of the 14th ACM Southeast Conference. ACM.
pp. 95–101. doi:10.1145/503561.503582 (https://doi.org/10.1145%2F503561.503582). Archived (https://web.ar
chive.org/web/20170312215255/http://dl.acm.org/citation.cfm?doid=503561.503582) from the original on 12
March 2017. Retrieved 29 June 2018.
2. Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Binary search".
3. Butterfield & Ngondi 2016, p. 46.
4. Cormen et al. 2009, p. 39.
5. Weisstein, Eric W. "Binary search" (https://mathworld.wolfram.com/BinarySearch.html). MathWorld.
6. Flores, Ivan; Madpis, George (1 September 1971). "Average binary search length for dense ordered lists".
Communications of the ACM. 14 (9): 602–603. doi:10.1145/362663.362752 (https://doi.org/10.1145%2F36266
3.362752). ISSN 0001-0782 (https://www.worldcat.org/issn/0001-0782). S2CID 43325465 (https://api.semantic
scholar.org/CorpusID:43325465).
7. Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Algorithm B".
8. Bottenbruch, Hermann (1 April 1962). "Structure and use of ALGOL 60". Journal of the ACM. 9 (2): 161–221.
doi:10.1145/321119.321120 (https://doi.org/10.1145%2F321119.321120). ISSN 0004-5411 (https://www.worldca
t.org/issn/0004-5411). S2CID 13406983 (https://api.semanticscholar.org/CorpusID:13406983). Procedure is
described at p. 214 (§43), titled "Program for Binary Search".
9. Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "History and bibliography".
10. Kasahara & Morishita 2006, pp. 8–9.
11. Sedgewick & Wayne 2011, §3.1, subsection "Rank and selection".
12. Goldman & Goldman 2008, pp. 461–463.
13. Sedgewick & Wayne 2011, §3.1, subsection "Range queries".
14. Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Further analysis of binary search".
15. Knuth 1998, §6.2.1 ("Searching an ordered table"), "Theorem B".
16. Chang 2003, p. 169.
17. Knuth 1997, §2.3.4.5 ("Path length").
18. Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Exercise 23".
19. Rolfe, Timothy J. (1997). "Analytic derivation of comparisons in binary search". ACM SIGNUM Newsletter. 32
(4): 15–19. doi:10.1145/289251.289255 (https://doi.org/10.1145%2F289251.289255). S2CID 23752485 (https://
api.semanticscholar.org/CorpusID:23752485).
20. Khuong, Paul-Virak; Morin, Pat (2017). "Array Layouts for Comparison-Based Searching". Journal of
Experimental Algorithmics. 22. Article 1.3. arXiv:1509.05053 (https://arxiv.org/abs/1509.05053).
doi:10.1145/3053370 (https://doi.org/10.1145%2F3053370). S2CID 23752485 (https://api.semanticscholar.org/
CorpusID:23752485).
21. Knuth 1997, §2.2.2 ("Sequential Allocation").
22. Beame, Paul; Fich, Faith E. (2001). "Optimal bounds for the predecessor problem and related problems" (http
s://doi.org/10.1006%2Fjcss.2002.1822). Journal of Computer and System Sciences. 65 (1): 38–72.
doi:10.1006/jcss.2002.1822 (https://doi.org/10.1006%2Fjcss.2002.1822).
https://en.wikipedia.org/wiki/Binary_search_algorithm 13/17
24.08.2021 Binary search algorithm - Wikipedia
https://en.wikipedia.org/wiki/Binary_search_algorithm 14/17
24.08.2021 Binary search algorithm - Wikipedia
53. Rényi, Alfréd (1961). "On a problem in information theory". Magyar Tudományos Akadémia Matematikai Kutató
Intézetének Közleményei (in Hungarian). 6: 505–516. MR 0143666 (https://www.ams.org/mathscinet-getitem?
mr=0143666).
54. Høyer, Peter; Neerbek, Jan; Shi, Yaoyun (2002). "Quantum complexities of ordered searching, sorting, and
element distinctness". Algorithmica. 34 (4): 429–448. arXiv:quant-ph/0102078 (https://arxiv.org/abs/quant-ph/01
02078). doi:10.1007/s00453-002-0976-3 (https://doi.org/10.1007%2Fs00453-002-0976-3). S2CID 13717616 (ht
tps://api.semanticscholar.org/CorpusID:13717616).
55. Childs, Andrew M.; Landahl, Andrew J.; Parrilo, Pablo A. (2007). "Quantum algorithms for the ordered search
problem via semidefinite programming". Physical Review A. 75 (3). 032335. arXiv:quant-ph/0608161 (https://ar
xiv.org/abs/quant-ph/0608161). Bibcode:2007PhRvA..75c2335C (https://ui.adsabs.harvard.edu/abs/2007PhRv
A..75c2335C). doi:10.1103/PhysRevA.75.032335 (https://doi.org/10.1103%2FPhysRevA.75.032335).
S2CID 41539957 (https://api.semanticscholar.org/CorpusID:41539957).
56. Grover, Lov K. (1996). A fast quantum mechanical algorithm for database search. 28th ACM Symposium on
Theory of Computing. Philadelphia, PA. pp. 212–219. arXiv:quant-ph/9605043 (https://arxiv.org/abs/quant-ph/9
605043). doi:10.1145/237814.237866 (https://doi.org/10.1145%2F237814.237866).
57. Peterson, William Wesley (1957). "Addressing for random-access storage". IBM Journal of Research and
Development. 1 (2): 130–146. doi:10.1147/rd.12.0130 (https://doi.org/10.1147%2Frd.12.0130).
58. "2n−1". OEIS A000225 (http://oeis.org/A000225) Archived (https://web.archive.org/web/20160608084228/http://
oeis.org/A000225) 8 June 2016 at the Wayback Machine. Retrieved 7 May 2016.
59. Lehmer, Derrick (1960). Teaching combinatorial tricks to a computer. Proceedings of Symposia in Applied
Mathematics. 10. pp. 180–181. doi:10.1090/psapm/010 (https://doi.org/10.1090%2Fpsapm%2F010).
60. Chazelle, Bernard; Guibas, Leonidas J. (1986). "Fractional cascading: I. A data structuring technique" (http://w
ww.cs.princeton.edu/~chazelle/pubs/FractionalCascading1.pdf) (PDF). Algorithmica. 1 (1–4): 133–162.
CiteSeerX 10.1.1.117.8349 (https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.117.8349).
doi:10.1007/BF01840440 (https://doi.org/10.1007%2FBF01840440). S2CID 12745042 (https://api.semanticsch
olar.org/CorpusID:12745042).
61. Chazelle, Bernard; Guibas, Leonidas J. (1986), "Fractional cascading: II. Applications" (http://www.cs.princeton.
edu/~chazelle/pubs/FractionalCascading2.pdf) (PDF), Algorithmica, 1 (1–4): 163–191,
doi:10.1007/BF01840441 (https://doi.org/10.1007%2FBF01840441), S2CID 11232235 (https://api.semanticsch
olar.org/CorpusID:11232235)
62. Bentley 2000, §4.1 ("The Challenge of Binary Search").
63. Pattis, Richard E. (1988). "Textbook errors in binary searching". SIGCSE Bulletin. 20: 190–194.
doi:10.1145/52965.53012 (https://doi.org/10.1145%2F52965.53012).
64. Bloch, Joshua (2 June 2006). "Extra, extra – read all about it: nearly all binary searches and mergesorts are
broken" (http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html). Google
Research Blog. Archived (https://web.archive.org/web/20160401140544/http://googleresearch.blogspot.com/20
06/06/extra-extra-read-all-about-it-nearly.html) from the original on 1 April 2016. Retrieved 21 April 2016.
65. Ruggieri, Salvatore (2003). "On computing the semi-sum of two integers" (http://www.di.unipi.it/~ruggieri/Paper
s/semisum.pdf) (PDF). Information Processing Letters. 87 (2): 67–71. CiteSeerX 10.1.1.13.5631 (https://citesee
rx.ist.psu.edu/viewdoc/summary?doi=10.1.1.13.5631). doi:10.1016/S0020-0190(03)00263-1 (https://doi.org/10.
1016%2FS0020-0190%2803%2900263-1). Archived (https://web.archive.org/web/20060703173514/http://ww
w.di.unipi.it/~ruggieri/Papers/semisum.pdf) (PDF) from the original on 3 July 2006. Retrieved 19 March 2016.
66. Bentley 2000, §4.4 ("Principles").
67. "bsearch – binary search a sorted table" (http://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.
html). The Open Group Base Specifications (7th ed.). The Open Group. 2013. Archived (https://web.archive.or
g/web/20160321211605/http://pubs.opengroup.org/onlinepubs/9699919799/functions/bsearch.html) from the
original on 21 March 2016. Retrieved 28 March 2016.
68. Stroustrup 2013, p. 945.
69. "std.range - D Programming Language" (https://dlang.org/phobos/std_range.html#SortedRange). dlang.org.
Retrieved 29 April 2020.
70. Unisys (2012), COBOL ANSI-85 programming reference manual, 1, pp. 598–601
71. "Package sort" (https://golang.org/pkg/sort/). The Go Programming Language. Archived (https://web.archive.or
g/web/20160425055919/https://golang.org/pkg/sort/) from the original on 25 April 2016. Retrieved 28 April
2016.
72. "java.util.Arrays" (https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html). Java Platform Standard
Edition 8 Documentation. Oracle Corporation. Archived (https://web.archive.org/web/20160429064301/http://do
cs.oracle.com/javase/8/docs/api/java/util/Arrays.html) from the original on 29 April 2016. Retrieved 1 May 2016.
73. "java.util.Collections" (https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html). Java Platform
Standard Edition 8 Documentation. Oracle Corporation. Archived (https://web.archive.org/web/2016042309242
4/https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html) from the original on 23 April 2016.
Retrieved 1 May 2016.
https://en.wikipedia.org/wiki/Binary_search_algorithm 15/17
24.08.2021 Binary search algorithm - Wikipedia
Sources
Bentley, Jon (2000). Programming pearls (2nd ed.). Addison-Wesley. ISBN 978-0-201-65788-3.
Butterfield, Andrew; Ngondi, Gerard E. (2016). A dictionary of computer science (7th ed.). Oxford, UK: Oxford
University Press. ISBN 978-0-19-968897-5.
Chang, Shi-Kuo (2003). Data structures and algorithms. Software Engineering and Knowledge Engineering. 13.
Singapore: World Scientific. ISBN 978-981-238-348-8.
Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009). Introduction to algorithms
(3rd ed.). MIT Press and McGraw-Hill. ISBN 978-0-262-03384-8.
Fitzgerald, Michael (2015). Ruby pocket reference. Sebastopol, California: O'Reilly Media. ISBN 978-1-4919-
2601-7.
Goldman, Sally A.; Goldman, Kenneth J. (2008). A practical guide to data structures and algorithms using Java.
Boca Raton, Florida: CRC Press. ISBN 978-1-58488-455-2.
Kasahara, Masahiro; Morishita, Shinichi (2006). Large-scale genome sequence processing. London, UK:
Imperial College Press. ISBN 978-1-86094-635-6.
Knuth, Donald (1997). Fundamental algorithms. The Art of Computer Programming. 1 (3rd ed.). Reading, MA:
Addison-Wesley Professional. ISBN 978-0-201-89683-1.
Knuth, Donald (1998). Sorting and searching. The Art of Computer Programming. 3 (2nd ed.). Reading, MA:
Addison-Wesley Professional. ISBN 978-0-201-89685-5.
Knuth, Donald (2011). Combinatorial algorithms. The Art of Computer Programming. 4A (1st ed.). Reading, MA:
Addison-Wesley Professional. ISBN 978-0-201-03804-0.
Moffat, Alistair; Turpin, Andrew (2002). Compression and coding algorithms. Hamburg, Germany: Kluwer
Academic Publishers. doi:10.1007/978-1-4615-0935-6 (https://doi.org/10.1007%2F978-1-4615-0935-6).
ISBN 978-0-7923-7668-2.
Sedgewick, Robert; Wayne, Kevin (2011). Algorithms (http://algs4.cs.princeton.edu/home/) (4th ed.). Upper
Saddle River, New Jersey: Addison-Wesley Professional. ISBN 978-0-321-57351-3. Condensed web version ;
book version .
Stroustrup, Bjarne (2013). The C++ programming language (4th ed.). Upper Saddle River, New Jersey:
Addison-Wesley Professional. ISBN 978-0-321-56384-2.
External links
NIST Dictionary of Algorithms and Data Structures: binary search (https://web.archive.org/web/2016110400573
9/https://xlinux.nist.gov/dads/HTML/binarySearch.html)
Comparisons and benchmarks of a variety of binary search implementations in C (https://sites.google.com/site/
binarysearchcube/binary-search)
https://en.wikipedia.org/wiki/Binary_search_algorithm 16/17
24.08.2021 Binary search algorithm - Wikipedia
https://en.wikipedia.org/wiki/Binary_search_algorithm 17/17