C Program to Perform Binary Search Using Recursion

In this article, We are going to talk about “C Program to Perform Binary Search Using Recursion”. Below, We can see the possibilities to perform this task. Let’s move.

C Program to Perform Binary Search Using Recursion

C Program to Perform Binary Search Using Recursion

Program Code

#include <stdio.h>
int binarySearch(int [], int, int, int);

int main()
{
  int c, first, last, n, search, array[100], index;

  printf("Enter number of elementsn");
  scanf("%d", &n);

  printf("Enter %d integersn", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  printf("Enter value to findn");
  scanf("%d", &search);

  first = 0;
  last = n - 1;

  index = binarySearch(array, first, last, search);
 
  if (index == -1)
    printf("Not found! %d isn't present in the list.n", search);
  else
    printf("%d is present at location %d.n", search, index + 1);
 
  return 0;
}

int binarySearch(int a[], int s, int e, int f) {
  int m;
 
  if (s > e) // Not found
     return -1;

  m = (s + e)/2;

  if (a[m] == f)  // element found
    return m;
  else if (f > a[m])  
    return binarySearch(a, m+1, e, f);
  else
    return binarySearch(a, s, m-1, f);
}

Conclusion

I hope this article helps you to know about “C Program to Perform Binary Search Using Recursion“. If you face any issues please let me know via the comment section. Share this article with other C/C++ developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment