Thursday, June 16, 2011

Algorithm and Program for Binary Search


implementation of the algorithm

limitations :
entered list must be pre shorted;
there must be only one element in the list which is to be searched;

#include<stdio.h>
#include<conio.h>
int mid;
int BinarySearch(int A[], int key, int low,int high)
{
       if (high < low)
        return -1;
      mid =low + (high - low)/2;
       if (A[mid] > key)
          return BinarySearch(A,key, low, mid-1);
       else if (A[mid] < key)
          return BinarySearch(A, key, mid+1, high);
       else
           return mid ;
   };
  
   int main()
   {
     
      int j,low=0,high=9,key,k=0;
      int A[9];
       printf("enter the 12 elements of array");
      for(j=0;j<9;j++)
      scanf("%d",&A[j]);
       printf("\n enter the element to be searched for");
      scanf("%d",&key);
      j=BinarySearch(A,key,low,high);
      if (j>=0)
      printf("\element %d is found at position %d",key,j+1); 
      else
      printf("\n element not found");
      getch();
      return 0;
   }
BinarySearch(A[0..N-1], value, low, high) {
       if (high < low)
           return -1 // not found
       mid = low + (high - low) / 2
       if (A[mid] > value)
           return BinarySearch(A, value, low, mid-1)
       else if (A[mid] < value)
           return BinarySearch(A, value, mid+1, high)
       else
           return mid // found
   }