Write a program to search an element using recursive binary search algorithm.


Name of the experiment:  Write a program to search an element using recursive binary search algorithm.


Algorithm:

1       Algorithm BinSrch( a, I, l, x)
2       {
3                 if ( l=i) then
4                 {
5                           if ( x= a[i]) then return I;
6                           else return 0;
7                 }
8                 else
9                 {


         11                        if ( x= a[mid]) then return mid;
12                        else if ( x< a[mid]) then
13                                  return BinSrch(a, I, mid-1, x);
14                        else return BinSrch( a, mid+1, l,x);
15               }
16     }










Source Code:
#include <stdio.h>

int RBinSrch(int a[], int low, int high, int x)
{
      int mid;
      if(low > high)
      {
            return -1;
      }
      mid = (low + high) / 2;
      if(x > a[mid])
      {
            RBinSrch(a, mid + 1, high, x);
      }
      else if(x < a[mid])
      {
            RBinSrch(a, low, mid - 1, x);
      }
      else
      {
            return mid;
      }
}

int main()
{
      int i, x, n, a[50], position;     
      printf("\nEnter the size of array:\t");
      scanf("%d", &n);
      printf("\nEnter %d elements in array: \n", n);
      for(i = 0; i < n; i++)
      {
            scanf("%d", &a[i]);
      }
      printf("\nEnter x To Search:\t");
      scanf("%d", &x);
      position = RBinSrch(a, 0, n - 1, x);
      if(position == -1)
      {
            printf("\nx %d Not Found\n", x);
      }
      else
      {
            printf("\nx %d Found at Position %d\n", x, position + 1);
      }
      return 0;
}

Sample Input and Output:
                  
                   Enter the size of array:          5
                   Enter 5 elements in array:
                   10   12   25   30   35

                   Enter X To Search:       30

                   X 30 Found at position         4








No comments

Dear Members, Thanks for Your Comments. We must be reply your comment answer as soon as possible. Please Stay with us.....

Theme images by ideabug. Powered by Blogger.