Signup/Sign In

C Program To Perform Binary Search Using Recursion

Learn C language tutorial

Logic To Perform Binary Search Using Recursion:

  • Binary Search is an efficient method to find the target value from the given ordered items,
  • In Binary Search the key given value is compared with the middle value, of an array, when the key value is less than or greater than the given array, the algorithm knows from where to search the given value.
  • The Binary Search process will continue until the given value is found, the algorithm will divide the the array size every time the value is not found
  • Binary Search will be successful when it found the given value.

Program To Perform Binary Search Using Recursion:

#include <stdio.h>
#include <stdlib.h>

void BinarySearch(int arr[],int num,int first,int last){
   
   int mid;

   if(first > last){
       
        printf("Cannot Find The Number");
        
   } else {
       
      
      mid = (first + last)/2;
    
      
      if(arr[mid]==num){
          
            printf("Element Is At The Index: %d ",mid);
            exit(0);
            
        }else if(arr[mid] > num){
            
            BinarySearch(arr, num, first, mid-1);
        
        }else{
            
            BinarySearch(arr, num, mid+1, last);
        }   
    }  
}


void main(){

   int arr[50],beg,mid,end,i,n,num;

   printf("Enter The Size Of The Given Array: ");
   scanf("%d",&n);

   printf("Enter The Values In Sorted Sequence \n");

   for(i=0;i<n;i++)
   {   
       scanf("%d",&arr[i]);
   }   


   beg=0;
   end=n-1;

   printf("Enter The Value To Search Using Binary Search: ");
   scanf("%d",&num);

   BinarySearch(arr,num,beg,end);

}

Output:

binary



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight