Pages

Custom Search

Monday, February 13, 2012

Binary Search recursive program.


Binary Search is a program where in the input array is sorted i.e., ascending order in this case. Every time the array is split into two parts and the middle element is compared with the key element to be searched.

Source Code:


 #include <stdio.h>  
 #include <stdlib.h>  
 int bin_srch(int a[], int n, int key, int low, int high)  
 {  
     int mid;  
     if(low <= high)  
    {  
         mid = (low + high)/2;  
         if(a[mid] == key)  
         {  
             return mid;  
          }  
          else if(key < a[mid])  
         {  
             return bin_srch(a, n, key, low, mid-1);  
          }  
          else if(key > a[mid])  
         {  
             return bin_srch(a, n, key, mid+1, high);  
          }  
     }  
     else  
     {  
          return -1;  
     }  
 }  
 int main()  
 {  
     int a[10], n, key, low, mid, high, i, indx;  
     printf("\nEnter size of array: ");  
     scanf("%d", &n);  
     printf("\nEnter elements of array: ");  
     for(i=0;i<n;i++)  
     {  
          scanf("%d", &a[i]);  
     }  
     printf("\nEnter the key element to be searched: ");  
     scanf("%d", &key);  
     low = 0;  
     high = n-1;  
     indx = bin_srch(a, n, key, low, high);  
     if(indx == -1)  
     {  
          printf("\nSearch unsuccessful");  
      }  
      else  
      {  
          printf("\nElement found at position %d\n\n", indx+1);  
      }  
 }  

2 comments:

Anonymous said...

I want to make 6 search algorithm this is look like binary search algorithm but not do 2 comparison it must do 6 comparison with recursive codes . if you help me , thankx a lot ...

Unknown said...

Awesome. I am a beginner and this article helped me to resolve the problem .Thank you author and the whole expect team.


http://www.wikitechy.com/view-article/simple-program-for-multiple-inheritance-using-cpp-with-example



Both are really good,
Cheers,
Venkat

Custom Search