This binary options guide pdf a good article. Follow the link for more information. This article is about searching a finite sorted array.
Visualization of the binary search algorithm where 7 is the target value. If the search ends with the remaining half being empty, the target is not in the array. Although the idea is simple, implementing binary search correctly requires attention to some subtleties about its exit conditions and midpoint calculation. There are numerous variations of binary search. Binary search works on sorted arrays. Binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned.
If the target value is less than or greater than the middle element, the search continues in the lower or upper half of the array, respectively, eliminating the other half from consideration. 1 and go to step 2. This iterative procedure keeps track of the search boundaries with the two variables. Some implementations may check whether the middle element is equal to the target at the end of the procedure.
This results in a faster comparison loop, but requires one more iteration on average. However, due to the ordered nature of sorted arrays, it is trivial to extend binary search to perform approximate matches. Rank queries can be performed using a modified version of binary search. Predecessor and successor queries can be performed with rank queries. The nearest neighbor of the target value is either its predecessor or successor, whichever is closer. Range queries are also straightforward.