This example implements a binary search, which finds the position of a target value within a sorted array.
It 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.
function binary_search( int A[], int n, int T )
L = 0
H = n − 1
while L ≤ H do
m = L + floor( ( H - L ) / 2 )
if A[m] < T
L = m + 1
else if A[m] > T
H = m − 1
else
return m
end if
end while
return unsuccessful
end function