Binary Search using Recursion in C

Write a program to implement binary search using recursion in c.

Given a sorted array, write a code to search an element in an array.

For example –

Example1 :  arr[] = {1, 3, 5, 6, 7}    target = 5

The element 5 is found at index 2.

We have given a sorted array, we can use binary search algorithm to search an element efficiently.

Binary Search

Binary Search is a searching algorithm that search an element in a sorted array in O(logN) time complexity.

In binary search, we first calculate the mid. In next step, we compare element present at mid index to the target value. If target value is found, we return the mid index. Else If the search value is less than or greater than the middle element, the search continues in the lower or upper half of the array.

Important Points

i) A Binary search algorithm is applicable only for sorted values. An array should be sorted either in ascending or descending order.

ii) The time complexity of binary search is O(log(n)).

In my previous post, I have discussed Binary search program in c using iterative approach. In this post, I am going to explain how to implement a binary search program in c using recursion.

Recursion vs Iteration – Difference between Recursion and Iteration

Recursion vs Iteration. What’s the difference between recursion and iteration.

Recursion and Iteration both are two different programming approaches. For some problems recursion is best suited and in some other cases iterative way of programming is good.

In programming, repeated set of instructions can be handled either by using recursive or iterative approach in our code. So which approach we choose and why? Let’s talk about the difference between iteration and recursion.

Recursion Concept with Example

What is recursion and how to use recursion in programming. If you are new to programming, then recursion concept is tough to understand. In this post, i’ll explain the concept of recursion with example.

What is Recursion ?

In Recursion, function call itself repeatedly, until the base or terminating condition is not true. To understand this statement let’s take an example.

Suppose, we have to print a number between start to end range. Let’s print number between 1 to 10.

It’s a much preferred way to write cleaner and shorter code for many complex problems.

Through recursion, you can reduce complex problem into smaller version.