Binary search in C using recursion

Posted on 16th April 2018

In my previous article C Program for Binary Search I explained how to use binary search algorithm to search an element in a sorted array. In that article you learnt how to implement binary search algorithm using C programing language. Today I'm going to show you how to implement binary search algorithm in C using recursion. Recursion is programming technique where a function calls itself to solve a smaller problem that is of the same type as the original problem. The recursive call (calling itself) continues until the function can produce a result trivially without making any more calls.

In the program below, the function binarysearch takes four parameters - the array to be searched, the lowest position of the search range, highest position of the search range, and the element to be searched.

The first time you call the binary search function with the entire range of the arra. So you set the lowest position to 0 and highest position to the length of the array minus one.

With each recursive call the search range becomes smaller and smaller until you find the search element.

Consider for example you want to search for 85 which is the sixth element (index position 5) in the array. In this case, the recursive calls to the binary search function will be performed as shown in the figure below.

As you can see the above diagram, the search range becomes smaller and smaller with each recursive call of binarysearch function. The first call to binarysearch function tries to find the search element in array position 0 to 9. In the second call you chop the array in two slices and perform the search on elements from 5 to 9. Search range on the third call is from position 5 to 6.