Binary search algorithm

In computer science, binary search, also known as half-interval search,[1] logarithmic search,[2] or binary chop,[3] is a search algorithm that finds the position of a target value within a sorted 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 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.
  • Procedure
Given an array {\displaystyle A}A of {\displaystyle n}n elements with values or records {\displaystyle A_{0},A_{1},A_{2},\ldots ,A_{n-1}}{\displaystyle A_{0},A_{1},A_{2},\ldots ,A_{n-1}}sorted such that {\displaystyle A_{0}\leq A_{1}\leq A_{2}\leq \cdots \leq A_{n-1}}{\displaystyle A_{0}\leq A_{1}\leq A_{2}\leq \cdots \leq A_{n-1}}, and target value {\displaystyle T}T, the following subroutine uses binary search to find the index of {\displaystyle T}T in {\displaystyle A}A.[7]

Set {\displaystyle L}L to {\displaystyle 0} 0 and {\displaystyle R}R to {\displaystyle n-1}n-1.
If {\displaystyle L>R}{\displaystyle L>R}, the search terminates as unsuccessful.
Set {\displaystyle m}m (the position of the middle element) to the floor of {\displaystyle {\frac {L+R}{2}}}{\displaystyle {\frac {L+R}{2}}}, which is the greatest integer less than or equal to {\displaystyle {\frac {L+R}{2}}}{\displaystyle {\frac {L+R}{2}}}.
If {\displaystyle A_{m}<T}{\displaystyle A_{m}<T}, set {\displaystyle L}L to {\displaystyle m+1}m+1 and go to step 2.
If {\displaystyle A_{m}>T}{\displaystyle A_{m}>T}, set {\displaystyle R}R to {\displaystyle m-1}m-1 and go to step 2.
Now {\displaystyle A_{m}=T}{\displaystyle A_{m}=T}, the search is done; return {\displaystyle m}m.
Posted on by