Wednesday, February 5, 2014

Binary Search

#include<stdio.h>         //Standard input/output header
// #include<conio.h>
  void main()
{
   int i,n,a[10],mid,low,high,key;
   // i is the looping variable
  // clrscr();
   printf("\n Enter the array size");
   scanf("%d",&n);        // Size of array is to be
                          // given as input (n)

   printf("Enter the array element in the ascending order");
   for(i=0;i<n;i++)
    {                  
     //The input array must be in ascending order
              // for a binary search.

     scanf("%d",&a[i]); //Input the array elements one-by-one
    }
   printf("\n Enter the key element to be searched");
   scanf("%d",&key);
   low=0;          // low is initialized to 0
   
high=n-1;       // high is initialized to the
   while(low<=high)
    {
      mid=(low+high)/2;     //Find the middle index in the array
      if(key==a[mid])
      {
        //if the required number(key)
        //is the mid element,
        //Element would be at location mid+1
        // as array starts with index 0.
       
       printf("The Element was found at position %d",mid+1);
       //getch();
       exit(0);             //Successful exit indicated by 0.
      }
     else if(key>a[mid])   // if key is found to be
      {             //bigger than mid,low must be made mid+1
        low=mid+1;    
       //so that search goes only between (mid+1) and (high)
     
}                            // elements in the array.
     else
      {
       //if key is found to be smaller than mid
       // then (high) must be made (mid-1)

        high=mid-1;    
       //so that search goes only between (low) and (mid-1)
     
}                           // elements in the array.
    }
  printf("\n Unsuccessful search\n");
  // getch();
 }



No comments:

Post a Comment