Implementation of binary search:
The binary search can be implemented as a recursive function. The recursive function below also implements this binary search algorithm. It receives four arguments: a sorted vector, and a key to search for, and the values of low and high (which, to start, will be 1 and the length of the vector). It will return -1 when the key is not in the vector, or the index of element in which it is found. The base cases in the algorithm are if low > high, that means the key is not in the vector, or whenever it is found. Or else, the common case I to adjust the range and call the binary search function again.
The illustrations of calling this function is shown here:
>> recbinsearch(svec, 5,1,length(svec))
ans =
3
>> recbinsearch(svec, 25,1,length(svec))
ans =
7
>> recbinsearch(svec, 4,1,length(svec))
ans =
-1