Thursday 9 August 2012

binary search implementation in c language using arrays

#include<stdio.h>
#include<conio.h>
int main()
{
    int i,key,a[]={1,5,9,11,23,43,56,59,78,99},l=0,h=9,mid;
    printf("enter a values to search:");
    scanf("%d",&key);
    while(l<=h)
    {
               mid=(l+h)/2;
               if(a[mid]==key)
               {
                              printf("search element is found at %d location",mid);
                              getch();
                              //exit(0);
                              return;
               }
               a[mid]>key?(h=mid-1):(l=h+1);
    }
    printf("search element is not found");
   getch();
   return 0;
}

No comments:

Post a Comment