Monday, February 10, 2014

C PROGRAM FOR BINARY SEARCH

/*C PROGRAM FOR BINARY SEARCH*/

#include<stdio.h>
#include<conio.h>
int main() {
int a[50],i,n,key,lb,ub,mid;
clrscr();
printf("Enter no. of terms=");
scanf("%d",&n);
printf("Enter the terms in ascending order:\n");
for(i=0;i<n;i++)
    scanf("%d", &a[i]);
lb = 0;
ub = n-1;
printf("Enter key to be searched=");
scanf("%d",&key);
mid = (lb+ub)/2;
while(lb<=ub){
    if(a[mid]<key)
    lb = mid +1;
    else if(a[mid]==key)
    {
    printf("%d found at location %d",key,mid+1);
    break;
    }
    else
    ub = mid - 1;
    mid = (lb+ub)/2;
}
if(lb>ub)
printf("%d is not found in the list",key);
getch();
return 0;
}

/*OUTPUT:
Enter no. of terms=4
Enter the terms in ascending order:
10
23
56
78
Enter key to be searched=56
56 found at location 3*/

No comments:

Post a Comment