Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Binary search

This article has been published in the peer-reviewed journal WikiJournal of Science (2019). Click to view the published version.
Featured article
From Wikipedia, the free encyclopedia
(Redirected fromBinary search algorithm)
Search algorithm finding the position of a target value within a sorted array
This article is about searching a finite sorted array. For searching continuous function values, seebisection method.

Binary search
Visualization of the binary search algorithm where 7 is the target value
ClassSearch algorithm
Data structureArray
Worst-caseperformanceO(logn)
Best-caseperformanceO(1)
AverageperformanceO(logn)
Worst-casespace complexityO(1)
OptimalYes

Incomputer science,binary search, also known ashalf-interval search,[1]logarithmic search,[2] orbinary chop,[3] is asearch algorithm that finds the position of a target value within asorted array.[4][5] 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.

Binary search runs inlogarithmic time in theworst case, makingO(logn){\displaystyle O(\log n)} comparisons, wheren{\displaystyle n} is the number of elements in the array.[a][6] Binary search is faster thanlinear search except for small arrays. However, the array must be sorted first to be able to apply binary search. There are specializeddata structures designed for fast searching, such ashash 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 finding the next-smallest or next-largest element in the array relative to the target even if it is absent from the array.

There are numerous variations of binary search. In particular,fractional cascading speeds up binary searches for the same value in multiple arrays. Fractional cascading efficiently solves a number of search problems incomputational geometry and in numerous other fields.Exponential search extends binary search to unbounded lists. Thebinary search tree andB-tree data structures are based on binary search.

Algorithm

[edit]

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

[edit]

Given an arrayA{\displaystyle A} ofn{\displaystyle n} elements with values orrecordsA0,A1,A2,,An1{\displaystyle A_{0},A_{1},A_{2},\ldots ,A_{n-1}}sorted such thatA0A1A2An1{\displaystyle A_{0}\leq A_{1}\leq A_{2}\leq \cdots \leq A_{n-1}}, and target valueT{\displaystyle T}, the followingsubroutine uses binary search to find the index ofT{\displaystyle T} inA{\displaystyle A}.[7]

  1. SetL{\displaystyle L} to0{\displaystyle 0} andR{\displaystyle R} ton1{\displaystyle n-1}.
  2. IfL>R{\displaystyle L>R}, the search terminates as unsuccessful.
  3. Setm{\displaystyle m} (the position of the middle element) toL{\displaystyle L} plus thefloor ofRL2{\displaystyle {\frac {R-L}{2}}}, which is the greatest integer less than or equal toRL2{\displaystyle {\frac {R-L}{2}}}.
  4. IfAm<T{\displaystyle A_{m}<T}, setL{\displaystyle L} tom+1{\displaystyle m+1} and go to step 2.
  5. IfAm>T{\displaystyle A_{m}>T}, setR{\displaystyle R} tom1{\displaystyle m-1} and go to step 2.
  6. NowAm=T{\displaystyle A_{m}=T}, the search is done; returnm{\displaystyle m}.

This iterative procedure keeps track of the search boundaries with the two variablesL{\displaystyle L} andR{\displaystyle R}. The procedure may be expressed inpseudocode as follows, where the variable names and types remain the same as above,floor is thefloor function, andunsuccessful refers to a specific value that conveys the failure of the search.[7]

binary-search
function binary_search(A, n, T)is    L := 0    R := n − 1while L ≤ Rdo        m := L + floor((R - L) / 2)if A[m] < Tthen            L := m + 1else if A[m] > Tthen            R := m − 1else:return mreturn unsuccessful

Alternatively, the algorithm may take theceiling ofRL2{\displaystyle {\frac {R-L}{2}}}. This may change the result if the target value appears more than once in the array.

Alternative procedure

[edit]

In the above procedure, the algorithm checks whether the middle element (m{\displaystyle m}) is equal to the target (T{\displaystyle T}) in every iteration. Some implementations leave out this check during each iteration. The algorithm would perform this check only when one element is left (whenL=R{\displaystyle L=R}). This results in a faster comparison loop, as one comparison is eliminated per iteration, while it requires only one more iteration on average.[8]

Hermann Bottenbruch published the first implementation to leave out this check in 1962.[8][9]

  1. SetL{\displaystyle L} to0{\displaystyle 0} andR{\displaystyle R} ton1{\displaystyle n-1}.
  2. WhileLR{\displaystyle L\neq R},
    1. Setm{\displaystyle m} (the position of the middle element) toL{\displaystyle L} plus theceiling ofRL2{\displaystyle {\frac {R-L}{2}}}, which is the least integer greater than or equal toRL2{\displaystyle {\frac {R-L}{2}}}.
    2. IfAm>T{\displaystyle A_{m}>T}, setR{\displaystyle R} tom1{\displaystyle m-1}.
    3. Else,AmT{\displaystyle A_{m}\leq T}; setL{\displaystyle L} tom{\displaystyle m}.
  3. NowL=R{\displaystyle L=R}, the search is done. IfAL=T{\displaystyle A_{L}=T}, returnL{\displaystyle L}. Otherwise, the search terminates as unsuccessful.

Whereceil is the ceiling function, the pseudocode for this version is:

function binary_search_alternative(A, n, T)is    L := 0    R := n − 1while L != Rdo        m := L + ceil((R - L) / 2)if A[m] > Tthen            R := m − 1else:            L := mif A[L] = Tthenreturn Lreturn unsuccessful

Duplicate elements

[edit]

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[1,2,3,4,4,5,6,7]{\displaystyle [1,2,3,4,4,5,6,7]} and the target was4{\displaystyle 4}, 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[1,2,4,4,4,5,6,7]{\displaystyle [1,2,4,4,4,5,6,7]} 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]

Procedure for finding the leftmost element

[edit]

To find the leftmost element, the following procedure can be used:[10]

  1. SetL{\displaystyle L} to0{\displaystyle 0} andR{\displaystyle R} ton{\displaystyle n}.
  2. WhileL<R{\displaystyle L<R},
    1. Setm{\displaystyle m} (the position of the middle element) toL{\displaystyle L} plus thefloor ofRL2{\displaystyle {\frac {R-L}{2}}}, which is the greatest integer less than or equal toRL2{\displaystyle {\frac {R-L}{2}}}.
    2. IfAm<T{\displaystyle A_{m}<T}, setL{\displaystyle L} tom+1{\displaystyle m+1}.
    3. Else,AmT{\displaystyle A_{m}\geq T}; setR{\displaystyle R} tom{\displaystyle m}.
  3. ReturnL{\displaystyle L}.

IfL<n{\displaystyle L<n} andAL=T{\displaystyle A_{L}=T}, thenAL{\displaystyle A_{L}} is the leftmost element that equalsT{\displaystyle T}. Even ifT{\displaystyle T} is not in the array,L{\displaystyle L} is therank ofT{\displaystyle T} in the array, or the number of elements in the array that are less thanT{\displaystyle T}.

Wherefloor is the floor function, the pseudocode for this version is:

function binary_search_leftmost(A, n, T):    L := 0    R := nwhile L < R:        m := L + floor((R - L) / 2)if A[m] < T:            L := m + 1else:            R := mreturn L

Procedure for finding the rightmost element

[edit]

To find the rightmost element, the following procedure can be used:[10]

  1. SetL{\displaystyle L} to0{\displaystyle 0} andR{\displaystyle R} ton{\displaystyle n}.
  2. WhileL<R{\displaystyle L<R},
    1. Setm{\displaystyle m} (the position of the middle element) toL{\displaystyle L} plus thefloor ofRL2{\displaystyle {\frac {R-L}{2}}}, which is the greatest integer less than or equal toRL2{\displaystyle {\frac {R-L}{2}}}.
    2. IfAm>T{\displaystyle A_{m}>T}, setR{\displaystyle R} tom{\displaystyle m}.
    3. Else,AmT{\displaystyle A_{m}\leq T}; setL{\displaystyle L} tom+1{\displaystyle m+1}.
  3. ReturnR1{\displaystyle R-1}.

IfR>0{\displaystyle R>0} andAR1=T{\displaystyle A_{R-1}=T}, thenAR1{\displaystyle A_{R-1}} is the rightmost element that equalsT{\displaystyle T}. Even ifT{\displaystyle T} is not in the array,nR{\displaystyle n-R} is the number of elements in the array that are greater thanT{\displaystyle T}.

Wherefloor is the floor function, the pseudocode for this version is:

function binary_search_rightmost(A, n, T):    L := 0    R := nwhile L < R:        m := L + floor((R - L) / 2)if A[m] > T:            R := melse:            L := m + 1return R - 1

Approximate matches

[edit]
Binary search can be adapted to compute approximate matches. In the example above, the rank, predecessor, successor, and nearest neighbor are shown for the target value5{\displaystyle 5}, which is not in the array.

The above procedure only performsexact matches, finding the position of a target value. However, it is trivial to extend binary search to perform approximate matches because binary search operates on sorted arrays. For example, binary search can be used to compute, for a given value, its rank (the number of smaller elements), predecessor (next-smallest element), successor (next-largest element), andnearest neighbor.Range queries seeking the number of elements between two values can be performed with two rank queries.[11]

  • Rank queries can be performed with theprocedure for finding the leftmost element. The number of elementsless than the target value is returned by the procedure.[11]
  • Predecessor queries can be performed with rank queries. If the rank of the target value isr{\displaystyle r}, its predecessor is r1{\displaystyle r-1}.[12]
  • For successor queries, theprocedure for finding the rightmost element can be used. If the result of running the procedure for the target value isr{\displaystyle r}, then the successor of the target value is r+1{\displaystyle r+1}.[12]
  • The nearest neighbor of the target value is either its predecessor or successor, whichever is closer.
  • 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

[edit]
Atree representing binary search. The array being searched here is[20,30,40,50,80,90,100]{\displaystyle [20,30,40,50,80,90,100]}, and the target value is40{\displaystyle 40}.
The worst case is reached when the search reaches the deepest level of the tree, while the best case is reached when the target value is the middle element.

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 worst case, binary search makeslog2(n)+1{\textstyle \lfloor \log _{2}(n)+1\rfloor } iterations of the comparison loop, where the{\textstyle \lfloor \cdot \rfloor } notation denotes thefloor function that yields the greatest integer less than or equal to the argument, andlog2{\textstyle \log _{2}} is thebinary logarithm. This is because the worst case is reached when the search reaches the deepest level of the tree, and there are alwayslog2(n)+1{\textstyle \lfloor \log _{2}(n)+1\rfloor } levels in the tree for any binary search.

The worst case may also be reached when the target element is not in the array. Ifn{\textstyle n} is one less than a power of two, then this is always the case. Otherwise, the search may performlog2(n)+1{\textstyle \lfloor \log _{2}(n)+1\rfloor }iterations if the search reaches the deepest level of the tree. However, it may makelog2(n){\textstyle \lfloor \log _{2}(n)\rfloor } iterations, which is one less than the worst case, if the search ends at the second-deepest level of the tree.[15]

On average, assuming that each element is equally likely to be searched, binary search makeslog2(n)+1(2log2(n)+1log2(n)2)/n{\displaystyle \lfloor \log _{2}(n)\rfloor +1-(2^{\lfloor \log _{2}(n)\rfloor +1}-\lfloor \log _{2}(n)\rfloor -2)/n} iterations when the target element is in the array. This is approximately equal tolog2(n)1{\displaystyle \log _{2}(n)-1} iterations. When the target element is not in the array, binary search makeslog2(n)+22log2(n)+1/(n+1){\displaystyle \lfloor \log _{2}(n)\rfloor +2-2^{\lfloor \log _{2}(n)\rfloor +1}/(n+1)} iterations on average, assuming that the range between and outside elements is equally likely to be searched.[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 overall 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

[edit]

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 isO(1){\displaystyle O(1)} in theword RAMmodel of computation.

Derivation of average case

[edit]

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 theintervals 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 byn{\displaystyle n}, 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 then+1{\displaystyle n+1} intervals.[14]

Successful searches

[edit]

In the binary tree representation, a successful search can be represented by a path from the root to the target node, called aninternal 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 lengthl, isl+1{\displaystyle l+1} counting the initial iteration. Theinternal 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 aren elements, which is a positive integer, and the internal path length isI(n){\displaystyle I(n)}, then the average number of iterations for a successful searchT(n)=1+I(n)n{\displaystyle T(n)=1+{\frac {I(n)}{n}}}, 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 withn nodes, which is equal to:[17]

I(n)=k=1nlog2(k){\displaystyle I(n)=\sum _{k=1}^{n}\left\lfloor \log _{2}(k)\right\rfloor }

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]

k=17log2(k)=0+2(1)+4(2)=2+8=10{\displaystyle \sum _{k=1}^{7}\left\lfloor \log _{2}(k)\right\rfloor =0+2(1)+4(2)=2+8=10}

The average number of iterations would be1+107=237{\displaystyle 1+{\frac {10}{7}}=2{\frac {3}{7}}} based on the equation for the average case. The sum forI(n){\displaystyle I(n)} can be simplified to:[14]

I(n)=k=1nlog2(k)=(n+1)log2(n+1)2log2(n+1)+1+2{\displaystyle I(n)=\sum _{k=1}^{n}\left\lfloor \log _{2}(k)\right\rfloor =(n+1)\left\lfloor \log _{2}(n+1)\right\rfloor -2^{\left\lfloor \log _{2}(n+1)\right\rfloor +1}+2}

Substituting the equation forI(n){\displaystyle I(n)} into the equation forT(n){\displaystyle T(n)}:[14]

T(n)=1+(n+1)log2(n+1)2log2(n+1)+1+2n=log2(n)+1(2log2(n)+1log2(n)2)/n{\displaystyle T(n)=1+{\frac {(n+1)\left\lfloor \log _{2}(n+1)\right\rfloor -2^{\left\lfloor \log _{2}(n+1)\right\rfloor +1}+2}{n}}=\lfloor \log _{2}(n)\rfloor +1-(2^{\lfloor \log _{2}(n)\rfloor +1}-\lfloor \log _{2}(n)\rfloor -2)/n}

For integern, this is equivalent to the equation for the average case on a successful search specified above.

Unsuccessful searches

[edit]

Unsuccessful searches can be represented by augmenting the tree withexternal nodes, which forms anextended 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. Anexternal path is a path from the root to an external node. Theexternal path length is the sum of the lengths of all unique external paths. If there aren{\displaystyle n} elements, which is a positive integer, and the external path length isE(n){\displaystyle E(n)}, then the average number of iterations for an unsuccessful searchT(n)=E(n)n+1{\displaystyle T'(n)={\frac {E(n)}{n+1}}}, with the one iteration added to count the initial iteration. The external path length is divided byn+1{\displaystyle n+1} instead ofn{\displaystyle n} because there aren+1{\displaystyle n+1} external paths, representing the intervals between and outside the elements of the array.[14]

This problem can similarly be reduced to determining the minimum external path length of all binary trees withn{\displaystyle n} nodes. For all binary trees, the external path length is equal to the internal path length plus2n{\displaystyle 2n}.[17] Substituting the equation forI(n){\displaystyle I(n)}:[14]

E(n)=I(n)+2n=[(n+1)log2(n+1)2log2(n+1)+1+2]+2n=(n+1)(log2(n)+2)2log2(n)+1{\displaystyle E(n)=I(n)+2n=\left[(n+1)\left\lfloor \log _{2}(n+1)\right\rfloor -2^{\left\lfloor \log _{2}(n+1)\right\rfloor +1}+2\right]+2n=(n+1)(\lfloor \log _{2}(n)\rfloor +2)-2^{\lfloor \log _{2}(n)\rfloor +1}}

Substituting the equation forE(n){\displaystyle E(n)} into the equation forT(n){\displaystyle T'(n)}, the average case for unsuccessful searches can be determined:[14]

T(n)=(n+1)(log2(n)+2)2log2(n)+1(n+1)=log2(n)+22log2(n)+1/(n+1){\displaystyle T'(n)={\frac {(n+1)(\lfloor \log _{2}(n)\rfloor +2)-2^{\lfloor \log _{2}(n)\rfloor +1}}{(n+1)}}=\lfloor \log _{2}(n)\rfloor +2-2^{\lfloor \log _{2}(n)\rfloor +1}/(n+1)}

Performance of alternative procedure

[edit]

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 onlylog2(n)+1{\textstyle \lfloor \log _{2}(n)+1\rfloor } times in the worst case, the slight increase in efficiency per iteration does not compensate for the extra iteration for all but very largen{\textstyle n}.[c][18][19]

Additional considerations

[edit]

Cost of comparison

[edit]

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 ofbits) 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, comparingfloating-point values (the most common digital representation ofreal numbers) is often more expensive than comparing integers or short strings.

Fast floating point comparison is possible via comparing as an integer. However, this kind of comparison forms atotal order, which makesevery floating-point value compare differently from each other and the same as itself. This is different from the typical comparison where -0.0 should be the same as 0.0 and NaN should not compare the same as any other value including itself.[20][21]

Branch prediction

[edit]

According toSteel Bank Common Lisp contributor Paul Khuong, binary search leads to very fewbranch mispredictions despite its data-dependent nature. This is in part because most of it can be expressed asconditional moves instead of branches. The same applies to most logarithmic divide-and-conquer search algorithms.[22]

Cache usage

[edit]

On most computer architectures, theprocessor has a hardwarecache separate fromRAM. 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 aslinear search andlinear probing inhash tables) which access elements in sequence. This adds slightly to the running time of binary search for large arrays on most systems.[23]

Paul Khuong has noted that binary search on large (≥ 512 KiB) arrays of exactly a power-of-two size tends to cause an additional problem with how CPU caches are implemented. Specifically, thetranslation lookaside buffer (TLB) is often implemented as acontent-addressable memory (CAM), with the "key" usually being the lower bits of a requested address. When searching on an array of exactly a power-of-two size,memory address with the same lower bits tend to be accessed, causing collisions ("aliasing") with the "key" used to fetch the CAM. The typical TLB is 4-way associative, meaning it can handle at most four addresses hitting the same "key", after whichTLB thrashing happens. (Although the other levels of CPU caches also use a similar setup, they manage smaller areas with a higher way count, usually 8 or 16, so they are less affected.) This can be prevented by offsetting the split point of the binary search so it divides at3164 instead of exactly the middle.[24]

Binary search versus other schemes

[edit]

Sorted arrays with binary search are a very inefficient solution when insertion and deletion operations are interleaved with retrieval, takingO(n){\textstyle O(n)} time for each such operation. In addition, sorted arrays can complicate memory use especially when elements are often inserted into the array.[25] There are other data structures that support much more efficient insertion and deletion. Binary search can be used to perform exact matching andset membership (determining whether a target value is in a collection of values). There are data structures that support faster exact matching and set membership. However, unlike many other searching schemes, binary search can be used for efficient approximate matching, usually performing such matches inO(logn){\textstyle O(\log n)} time regardless of the type or structure of the values themselves.[26] In addition, there are some operations, like finding the smallest and largest element, that can be performed efficiently on a sorted array.[11]

Linear search

[edit]

Linear search is a simple search algorithm that checks every record until it finds the target value. Linear search can be done on alinked 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][28] Allsorting algorithms based on comparing elements, such asquicksort andmerge sort, require at leastO(nlogn){\textstyle O(n\log n)} comparisons in the worst case.[29] 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.[30]

Trees

[edit]
Binary search trees are searched using an algorithm similar to binary search.

Abinary search tree is abinary 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.[26][31]

However, binary search is usually more efficient for searching as binary search trees will most likely be imperfectly balanced, resulting in slightly worse performance than binary search. This even applies tobalanced binary search trees, binary search trees that balance their own nodes, because they rarely 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 approachingn{\textstyle n} comparisons.[e] Binary search trees take more space than sorted arrays.[33]

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. TheB-tree generalizes this method of tree organization. B-trees are frequently used to organize long-term storage such asdatabases andfilesystems.[34][35]

Hashing

[edit]

For implementingassociative arrays,hash tables, a data structure that maps keys torecords using ahash function, are generally faster than binary search on a sorted array of records.[36] Most hash table implementations require onlyamortized constant time on average.[f][38] 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.[39] 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.[26]

Set membership algorithms

[edit]

A related problem to search isset 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. Abit array is the simplest, useful when the range of keys is limited. It compactly stores a collection ofbits, with each bit representing a single key within the range of keys. Bit arrays are very fast, requiring onlyO(1){\textstyle O(1)} time.[40] The Judy1 type ofJudy array handles 64-bit keys efficiently.[41]

For approximate results,Bloom filters, another probabilistic data structure based on hashing, store aset of keys by encoding the keys using abit array and multiple hash functions. Bloom filters are much more space-efficient than bit arrays in most cases and not much slower: withk{\textstyle k} hash functions, membership queries require onlyO(k){\textstyle O(k)} time. However, Bloom filters suffer fromfalse positives.[g][h][43]

Other data structures

[edit]

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 asvan Emde Boas trees,fusion trees,tries, andbit 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.[26] 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.[41]

Variations

[edit]

Uniform binary search

[edit]
Main article:Uniform binary search
Uniform binary search stores the difference between the current and the two next possible middle elements instead of specific bounds.

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. Alookup table containing the differences is computed beforehand. For example, if the array to be searched is[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], the middle element (m{\displaystyle m}) would be6. In this case, the middle element of the left subarray ([1, 2, 3, 4, 5]) is3 and the middle element of the right subarray ([7, 8, 9, 10, 11]) is9. Uniform binary search would store the value of3 as both indices differ from6 by this same amount.[44] 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 ondecimal computers.[45]

Exponential search

[edit]
Main article:Exponential search
Visualization ofexponential searching finding the upper bound for the subsequent binary search

Exponential search extends binary search to unbounded lists. It starts by finding the first element with an index that is both a power of two and greater than the target value. Afterwards, it sets that index as the upper bound, and switches to binary search. A search takeslog2x+1{\textstyle \lfloor \log _{2}x+1\rfloor } iterations before binary search is started and at mostlog2x{\textstyle \lfloor \log _{2}x\rfloor } iterations of the binary search, wherex{\textstyle x} is the position of the target value. Exponential search works on bounded lists, but becomes an improvement over binary search only if the target value lies near the beginning of the array.[46]

Interpolation search

[edit]
Main article:Interpolation search
Visualization ofinterpolation search using linear interpolation. In this case, no searching is needed because the estimate of the target's location within the array is correct. Other implementations may specify another function for estimating the target's location.

Instead of calculating the midpoint, interpolation search estimates the position of the target value, taking into account the lowest and highest elements in the array as well as length of the array. It works on the basis that the midpoint is not the best guess in many cases. For example, if the target value is close to the highest element in the array, it is likely to be located near the end of the array.[47]

A common interpolation function islinear interpolation. IfA{\displaystyle A} is the array,L,R{\displaystyle L,R} are the lower and upper bounds respectively, andT{\displaystyle T} is the target, then the target is estimated to be about(TAL)/(ARAL){\displaystyle (T-A_{L})/(A_{R}-A_{L})} of the way betweenL{\displaystyle L} andR{\displaystyle R}. When linear interpolation is used, and the distribution of the array elements is uniform or near uniform, interpolation search makesO(loglogn){\textstyle O(\log \log n)} comparisons.[47][48][49]

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.[47]

Fractional cascading

[edit]
Main article:Fractional cascading
Infractional cascading, each array has pointers to every second element of another array, so only one binary search has to be performed to search all the arrays.

Fractional cascading is a technique that speeds up binary searches for the same element in multiple sorted arrays. Searching each array separately requiresO(klogn){\textstyle O(k\log n)} time, wherek{\textstyle k} is the number of arrays. Fractional cascading reduces this toO(k+logn){\textstyle O(k+\log n)} by storing specific information in each array about each element and its position in the other arrays.[50][51]

Fractional cascading was originally developed to efficiently solve variouscomputational geometry problems. Fractional cascading has been applied elsewhere, such as indata mining andInternet Protocol routing.[50]

Generalization to graphs

[edit]

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 inO(logn){\displaystyle O(\log n)} queries in the worst case.[52]

Noisy binary search

[edit]
In noisy binary search, there is a certain probability that a comparison is incorrect.

Noisy binary search algorithms solve the case where the algorithm cannot reliably compare elements of the array. For each pair of elements, there is a certain probability that the algorithm makes the wrong comparison. Noisy binary search can find the correct position of the target with a given probability that controls the reliability of the yielded position. Every noisy binary search procedure must make at least(1τ)log2(n)H(p)10H(p){\displaystyle (1-\tau ){\frac {\log _{2}(n)}{H(p)}}-{\frac {10}{H(p)}}} comparisons on average, whereH(p)=plog2(p)(1p)log2(1p){\displaystyle H(p)=-p\log _{2}(p)-(1-p)\log _{2}(1-p)} is thebinary entropy function andτ{\displaystyle \tau } is the probability that the procedure yields the wrong position.[53][54][55] The noisy binary search problem can be considered as a case of theRényi-Ulam game,[56] a variant ofTwenty Questions where the answers may be wrong.[57]

Quantum binary search

[edit]

Classical computers are bounded to the worst case of exactlylog2n+1{\textstyle \lfloor \log _{2}n+1\rfloor } iterations when performing binary search.Quantum algorithms for binary search are still bounded to a proportion oflog2n{\textstyle \log _{2}n} queries (representing iterations of the classical procedure), but the constant factor is less than one, providing for a lower time complexity onquantum computers. Anyexact quantum binary search procedure—that is, a procedure that always yields the correct result—requires at least1π(lnn1)0.22log2n{\textstyle {\frac {1}{\pi }}(\ln n-1)\approx 0.22\log _{2}n} queries in the worst case, whereln{\textstyle \ln } is thenatural logarithm.[58] There is an exact quantum binary search procedure that runs in4log605n0.433log2n{\textstyle 4\log _{605}n\approx 0.433\log _{2}n} queries in the worst case.[59] In comparison,Grover's algorithm is the optimal quantum algorithm for searching an unordered list of elements, and it requiresO(n){\displaystyle O({\sqrt {n}})} queries.[60]

History

[edit]

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 toc. 200 BCE. The tablet contained about 500sexagesimal numbers and theirreciprocals sorted inlexicographical 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 theAegean 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 theMoore School Lectures, a seminal and foundational college course in computing.[9] In 1957,William Wesley Peterson published the first method for interpolation search.[9][61] Every published binary search algorithm worked only for arrays whose length is one less than a power of two[i] until 1960, whenDerrick Henry Lehmer published a binary search algorithm that worked on all arrays.[63] In 1962, Hermann Bottenbruch presented anALGOL 60 implementation of binary search that placed thecomparison for equality at the end, increasing the average number of iterations by one, but reducing to one the number of comparisons per iteration.[8] Theuniform binary search was developed by A. K. Chandra ofStanford University in 1971.[9] In 1986,Bernard Chazelle andLeonidas J. Guibas introducedfractional cascading as a method to solve numerous search problems incomputational geometry.[50][64][65]

Implementation issues

[edit]

Although the basic idea of binary search is comparatively straightforward, the details can be surprisingly tricky

— Donald Knuth[2]

WhenJon 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 rareedge cases.[66] A study published in 1988 shows that accurate code for it is only found in five out of twenty textbooks.[67] Furthermore, Bentley's own implementation of binary search, published in his 1986 bookProgramming Pearls, contained anoverflow error that remained undetected for over twenty years. TheJava programming language library implementation of binary search had the same overflow bug for more than nine years.[68]

In a practical implementation, the variables used to represent the indices will often be of fixed size (integers), and this can result in anarithmetic overflow for very large arrays. If the midpoint of the span is calculated asL+R2{\displaystyle {\frac {L+R}{2}}}, then the value ofL+R{\displaystyle L+R} may exceed the range of integers of the data type used to store the midpoint, even ifL{\displaystyle L} andR{\displaystyle R} are within the range. IfL{\displaystyle L} andR{\displaystyle R} are nonnegative, this can be avoided by calculating the midpoint asL+RL2{\displaystyle L+{\frac {R-L}{2}}}.[69]

An infinite loop may occur if the exit conditions for the loop are not defined correctly. OnceL{\displaystyle L} exceedsR{\displaystyle R}, 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][70]

Library support

[edit]

Many languages'standard libraries include binary search routines:

  • C provides thefunctionbsearch() in itsstandard library, which is typically implemented via binary search, although the official standard does not require it so.[71]
  • C++'sstandard library provides the functionsbinary_search(),lower_bound(),upper_bound() andequal_range().[72] Using theC++20std::ranges library, it can be applied over arange asstd::ranges::binary_search().
  • D's standard library Phobos, instd.range module provides a typeSortedRange (returned bysort() andassumeSorted() functions) with methodscontains(),equaleRange(),lowerBound() andtrisect(), that use binary search techniques by default for ranges that offer random access.[73]
  • COBOL provides theSEARCH ALL verb for performing binary searches on COBOL ordered tables.[74]
  • Go'ssort standard library package contains the functionsSearch,SearchInts,SearchFloat64s, andSearchStrings, which implement general binary search, as well as specific implementations for searching slices of integers, floating-point numbers, and strings, respectively.[75]
  • Java offers a set ofoverloadedbinarySearch() static methods in the classesArrays andCollections in the standardjava.util package for performing binary searches on Java arrays and onLists, respectively.[76][77]
  • Microsoft's.NET Framework 2.0 offers staticgeneric versions of the binary search algorithm in its collection base classes. An example would beSystem.Array's methodBinarySearch<T>(T[] array, T value).[78]
  • ForObjective-C, theCocoa framework provides theNSArray-indexOfObject:inSortedRange:options:usingComparator: method in Mac OS X 10.6+.[79] Apple'sCore Foundation C framework also contains aCFArrayBSearchValues() function.[80]
  • Python provides thebisect module that keeps a list in sorted order without having to sort the list after each insertion.[81]
  • Ruby's Array class includes absearch method with built-in approximate matching.[82]
  • Rust's slice primitive providesbinary_search(),binary_search_by(),binary_search_by_key(), andpartition_point().[83]

See also

[edit]
  • 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 and references

[edit]

This article was submitted toWikiJournal of Science for externalacademic peer review in 2018 (reviewer reports). The updated content was reintegrated into the Wikipedia page under aCC-BY-SA-3.0 license (2019). The version of record as reviewed is:Anthony Lin; et al. (2 July 2019)."Binary search algorithm"(PDF).WikiJournal of Science.2 (1): 5.doi:10.15347/WJS/2019.005.ISSN 2470-6345.Wikidata Q81434400.

Notes

[edit]
  1. ^TheO{\displaystyle O} isBig O notation, andlog{\displaystyle \log } is thelogarithm. 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,logb(n)=logk(n)÷logk(b){\displaystyle \log _{b}(n)=\log _{k}(n)\div \log _{k}(b)}, wherelogk(b){\displaystyle \log _{k}(b)} is a constant.
  2. ^Any search algorithm based solely on comparisons can be represented using a binary comparison tree. Aninternal path is any path from the root to an existing node. LetI{\displaystyle I} be theinternal path length, the sum of the lengths of all internal paths. If each element is equally likely to be searched, the average case is1+In{\displaystyle 1+{\frac {I}{n}}} 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 iterationsafter 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 lengthI{\displaystyle I} must be minimized. It turns out that the tree for binary search minimizes the internal path length.Knuth 1998 proved that theexternal 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 lengthI{\displaystyle I} is linearly related to external path lengthE{\displaystyle E}. For any tree ofn{\displaystyle n} nodes,I=E2n{\displaystyle I=E-2n}. 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]
  3. ^Knuth 1998 showed on hisMIX computer model, which Knuth designed as a representation of an ordinary computer, that the average running time of this variation for a successful search is17.5log2n+17{\textstyle 17.5\log _{2}n+17} units of time compared to18log2n16{\textstyle 18\log _{2}n-16} units for regular binary search. The time complexity for this variation grows slightly more slowly, but at the cost of higher initial complexity.[18]
  4. ^Knuth 1998 performed a formal time performance analysis of both of these search algorithms. On Knuth'sMIX computer, which Knuth designed as a representation of an ordinary computer, binary search takes on average18logn16{\textstyle 18\log n-16} units of time for a successful search, while linear search with a sentinel node at the end of the list takes1.75n+8.5n mod 24n{\textstyle 1.75n+8.5-{\frac {n{\text{ mod }}2}{4n}}} 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 ifn>44{\textstyle n>44}.[14][27]
  5. ^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.[32]
  6. ^It is possible to search some hash table implementations in guaranteed constant time.[37]
  7. ^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.[42]
  8. ^There exist improvements of the Bloom filter which improve on its complexity or support deletion; for example, the cuckoo filter exploitscuckoo hashing to gain these advantages.[42]
  9. ^That is, arrays of length 1, 3, 7, 15, 31 ...[62]

Citations

[edit]
  1. ^Williams, Jr., Louis F. (22 April 1976).A modification to the half-interval search (binary search) method. Proceedings of the 14th ACM Southeast Conference. ACM. pp. 95–101.doi:10.1145/503561.503582.Archived from the original on 12 March 2017. Retrieved29 June 2018.
  2. ^abKnuth 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".MathWorld.
  6. ^abFlores, 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.ISSN 0001-0782.S2CID 43325465.
  7. ^abcKnuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Algorithm B".
  8. ^abcdBottenbruch, Hermann (1 April 1962)."Structure and use of ALGOL 60".Journal of the ACM.9 (2):161–221.doi:10.1145/321119.321120.ISSN 0004-5411.S2CID 13406983. Procedure is described at p. 214 (§43), titled "Program for Binary Search".
  9. ^abcdefKnuth 1998, §6.2.1 ("Searching an ordered table"), subsection "History and bibliography".
  10. ^abKasahara & Morishita 2006, pp. 8–9.
  11. ^abcSedgewick & Wayne 2011, §3.1, subsection "Rank and selection".
  12. ^abcGoldman & Goldman 2008, pp. 461–463.
  13. ^Sedgewick & Wayne 2011, §3.1, subsection "Range queries".
  14. ^abcdefghijklKnuth 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. ^abcKnuth 1997, §2.3.4.5 ("Path length").
  18. ^abKnuth 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.S2CID 23752485.
  20. ^Herf, Michael (December 2001)."radix tricks".stereopsis: graphics.
  21. ^"Implement total_cmp for f32, f64 by golddranks · Pull Request #72568 · rust-lang/rust".GitHub. – contains relevant quotations from IEEE 754-2008 and -2019. Contains a type-pun implementation and explanation.
  22. ^"Binary search *eliminates* branch mispredictions - Paul Khuong: some Lisp".pvk.ca.
  23. ^Khuong, Paul-Virak;Morin, Pat (2017). "Array Layouts for Comparison-Based Searching".Journal of Experimental Algorithmics.22. Article 1.3.arXiv:1509.05053.doi:10.1145/3053370.S2CID 23752485.
  24. ^"Binary search is a pathological case for caches - Paul Khuong: some Lisp".pvk.ca.
  25. ^Knuth 1997, §2.2.2 ("Sequential Allocation").
  26. ^abcdBeame, Paul;Fich, Faith E. (2001)."Optimal bounds for the predecessor problem and related problems".Journal of Computer and System Sciences.65 (1):38–72.doi:10.1006/jcss.2002.1822.
  27. ^Knuth 1998, Answers to Exercises (§6.2.1) for "Exercise 5".
  28. ^Knuth 1998, §6.2.1 ("Searching an ordered table").
  29. ^Knuth 1998, §5.3.1 ("Minimum-Comparison sorting").
  30. ^Sedgewick & Wayne 2011, §3.2 ("Ordered symbol tables").
  31. ^Sedgewick & Wayne 2011, §3.2 ("Binary Search Trees"), subsection "Order-based methods and deletion".
  32. ^Knuth 1998, §6.2.2 ("Binary tree searching"), subsection "But what about the worst case?".
  33. ^Sedgewick & Wayne 2011, §3.5 ("Applications"), "Which symbol-table implementation should I use?".
  34. ^Knuth 1998, §5.4.9 ("Disks and Drums").
  35. ^Knuth 1998, §6.2.4 ("Multiway trees").
  36. ^Knuth 1998, §6.4 ("Hashing").
  37. ^Knuth 1998, §6.4 ("Hashing"), subsection "History".
  38. ^Dietzfelbinger, Martin;Karlin, Anna;Mehlhorn, Kurt; Meyer auf der Heide, Friedhelm; Rohnert, Hans;Tarjan, Robert E. (August 1994). "Dynamic perfect hashing: upper and lower bounds".SIAM Journal on Computing.23 (4):738–761.doi:10.1137/S0097539791194094.
  39. ^Morin, Pat."Hash tables"(PDF). p. 1.Archived(PDF) from the original on 9 October 2022. Retrieved28 March 2016.
  40. ^Knuth 2011, §7.1.3 ("Bitwise Tricks and Techniques").
  41. ^abSilverstein, Alan,Judy IV shop manual(PDF),Hewlett-Packard, pp. 80–81,archived(PDF) from the original on 9 October 2022
  42. ^abFan, Bin; Andersen, Dave G.; Kaminsky, Michael; Mitzenmacher, Michael D. (2014).Cuckoo filter: practically better than Bloom. Proceedings of the 10th ACM International on Conference on Emerging Networking Experiments and Technologies. pp. 75–88.doi:10.1145/2674005.2674994.
  43. ^Bloom, Burton H. (1970). "Space/time trade-offs in hash coding with allowable errors".Communications of the ACM.13 (7):422–426.CiteSeerX 10.1.1.641.9096.doi:10.1145/362686.362692.S2CID 7931252.
  44. ^Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "An important variation".
  45. ^Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Algorithm U".
  46. ^Moffat & Turpin 2002, p. 33.
  47. ^abcKnuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Interpolation search".
  48. ^Knuth 1998, §6.2.1 ("Searching an ordered table"), subsection "Exercise 22".
  49. ^Perl, Yehoshua; Itai, Alon; Avni, Haim (1978)."Interpolation search—a log logn search".Communications of the ACM.21 (7):550–553.doi:10.1145/359545.359557.S2CID 11089655.
  50. ^abcChazelle, Bernard; Liu, Ding (6 July 2001).Lower bounds for intersection searching and fractional cascading in higher dimension. 33rdACM Symposium on Theory of Computing. ACM. pp. 322–329.doi:10.1145/380752.380818.ISBN 978-1-58113-349-3. Retrieved30 June 2018.
  51. ^Chazelle, Bernard; Liu, Ding (1 March 2004)."Lower bounds for intersection searching and fractional cascading in higher dimension"(PDF).Journal of Computer and System Sciences.68 (2):269–284.CiteSeerX 10.1.1.298.7772.doi:10.1016/j.jcss.2003.07.003.ISSN 0022-0000.Archived(PDF) from the original on 9 October 2022. Retrieved30 June 2018.
  52. ^Emamjomeh-Zadeh, Ehsan; Kempe, David; Singhal, Vikrant (2016).Deterministic and probabilistic binary search in graphs. 48thACM Symposium on Theory of Computing. pp. 519–532.arXiv:1503.00805.doi:10.1145/2897518.2897656.
  53. ^Ben-Or, Michael; Hassidim, Avinatan (2008)."The Bayesian learner is optimal for noisy binary search (and pretty good for quantum as well)"(PDF).49thSymposium on Foundations of Computer Science. pp. 221–230.doi:10.1109/FOCS.2008.58.ISBN 978-0-7695-3436-7.Archived(PDF) from the original on 9 October 2022.
  54. ^Pelc, Andrzej (1989)."Searching with known error probability".Theoretical Computer Science.63 (2):185–202.doi:10.1016/0304-3975(89)90077-7.
  55. ^Rivest, Ronald L.;Meyer, Albert R.;Kleitman, Daniel J.; Winklmann, K.Coping with errors in binary search procedures. 10thACM Symposium on Theory of Computing.doi:10.1145/800133.804351.
  56. ^Pelc, Andrzej (2002)."Searching games with errors—fifty years of coping with liars".Theoretical Computer Science.270 (1–2):71–109.doi:10.1016/S0304-3975(01)00303-6.
  57. ^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.
  58. ^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.doi:10.1007/s00453-002-0976-3.S2CID 13717616.
  59. ^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.Bibcode:2007PhRvA..75c2335C.doi:10.1103/PhysRevA.75.032335.S2CID 41539957.
  60. ^Grover, Lov K. (1996).A fast quantum mechanical algorithm for database search. 28thACM Symposium on Theory of Computing. Philadelphia, PA. pp. 212–219.arXiv:quant-ph/9605043.doi:10.1145/237814.237866.
  61. ^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.
  62. ^"2n−1".OEISA000225Archived 8 June 2016 at theWayback Machine. Retrieved 7 May 2016.
  63. ^Lehmer, Derrick (1960). "Teaching combinatorial tricks to a computer".Combinatorial Analysis. Proceedings of Symposia in Applied Mathematics. Vol. 10. pp. 180–181.doi:10.1090/psapm/010/0113289.ISBN 9780821813102.MR 0113289.{{cite book}}:ISBN / Date incompatibility (help)
  64. ^Chazelle, Bernard;Guibas, Leonidas J. (1986)."Fractional cascading: I. A data structuring technique"(PDF).Algorithmica.1 (1–4):133–162.CiteSeerX 10.1.1.117.8349.doi:10.1007/BF01840440.S2CID 12745042.
  65. ^Chazelle, Bernard;Guibas, Leonidas J. (1986),"Fractional cascading: II. Applications"(PDF),Algorithmica,1 (1–4):163–191,doi:10.1007/BF01840441,S2CID 11232235
  66. ^Bentley 2000, §4.1 ("The Challenge of Binary Search").
  67. ^Pattis, Richard E. (1988). "Textbook errors in binary searching".SIGCSE Bulletin.20:190–194.doi:10.1145/52965.53012.
  68. ^Bloch, Joshua (2 June 2006)."Extra, extra – read all about it: nearly all binary searches and mergesorts are broken".Google Research Blog.Archived from the original on 1 April 2016. Retrieved21 April 2016.
  69. ^Ruggieri, Salvatore (2003)."On computing the semi-sum of two integers"(PDF).Information Processing Letters.87 (2):67–71.CiteSeerX 10.1.1.13.5631.doi:10.1016/S0020-0190(03)00263-1.Archived(PDF) from the original on 3 July 2006. Retrieved19 March 2016.
  70. ^Bentley 2000, §4.4 ("Principles").
  71. ^"bsearch – binary search a sorted table".The Open Group Base Specifications (7th ed.).The Open Group. 2013.Archived from the original on 21 March 2016. Retrieved28 March 2016.
  72. ^Stroustrup 2013, p. 945.
  73. ^"std.range - D Programming Language".dlang.org. Retrieved29 April 2020.
  74. ^Unisys (2012),COBOL ANSI-85 programming reference manual, vol. 1, pp. 598–601
  75. ^"Package sort".The Go Programming Language.Archived from the original on 25 April 2016. Retrieved28 April 2016.
  76. ^"java.util.Arrays".Java Platform Standard Edition 8 Documentation.Oracle Corporation.Archived from the original on 29 April 2016. Retrieved1 May 2016.
  77. ^"java.util.Collections".Java Platform Standard Edition 8 Documentation.Oracle Corporation.Archived from the original on 23 April 2016. Retrieved1 May 2016.
  78. ^"List<T>.BinarySearch method (T)".Microsoft Developer Network.Archived from the original on 7 May 2016. Retrieved10 April 2016.
  79. ^"NSArray".Mac Developer Library.Apple Inc.Archived from the original on 17 April 2016. Retrieved1 May 2016.
  80. ^"CFArray".Mac Developer Library.Apple Inc.Archived from the original on 20 April 2016. Retrieved1 May 2016.
  81. ^"8.6. bisect — Array bisection algorithm".The Python Standard Library. Python Software Foundation.Archived from the original on 25 March 2018. Retrieved26 March 2018.
  82. ^Fitzgerald 2015, p. 152.
  83. ^"Primitive Typeslice".The Rust Standard Library.The Rust Foundation. 2024. Retrieved25 May 2024.

Sources

[edit]

External links

[edit]
The WikibookAlgorithm implementation has a page on the topic of:Binary search
Data structures
Algorithms andalgorithmic paradigms
Retrieved from "https://en.wikipedia.org/w/index.php?title=Binary_search&oldid=1323008056"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp