In this program, we will be learning how to perform a binary search using recursion. A function is defined to perform binary search in the given array.
The main task is to search for a sorted array repeatedly by dividing the search interval by half.
If the search value is less than the middle item then narrow the interval to the lower half. Otherwise, narrow it to the upper half. Here, we need to continuously check for the result whether it is present or not.
- The term and first term is initialized 4 and 0 respectively.
- Array b is defined and length of b is stored in a variable named last.
- Define a function binary(a,fir,las,term).
- Check if term is greater than middle term, then call the function binary(a, mid, las,term) recursively.
- Else if the term is less than the middle term then call the function binary(a,fir, mid, term)
- Else if the term is equal to the middle term print “number found” with index at mid+1
- Else print “number is not there in the array”
def binary(a, fir, las, term):
binary(a, mid, las, term)
binary(a,fir, mid, term)
print("Number found at", mid+1)
print("Number is not there in the array")
Number found at 4