Friday, May 28, 2010

Binary Search Method

#include< stdio.h>
#include < conio.h>
//global declaration of varaible
int a[20],ub,lb,mid, i,n, s,found=0;

void main()
{
printf("\nEnter Total Number of Elements =");
scanf("%d",&n);

//enter array elements
for(i=0;i< n;i=i+1)
{
scanf("%d",&a[i]);
}

printf("\nEnter Element to be Searched = ");
scanf("%d",&s);

//initialise
lb=0;
ub=n-1;
mid=(lb+ub)/2;

//search data
while (lb < =ub)
{
    if (a[mid]= =s)
    {
        found=1;
        printf("Element %d found at postion %d,",s,mid+1);
        break;
    }
    if(a[mid] <  s)
    {
        lb=mid+1;
    }
    if(s < a[mid])
    {
        ub=mid-1;
    }
    mid=(lb+ub)/2;
}
if(found= =0)
{
    printf("\n Element Not Found.");
}
}

No comments:

Post a Comment