/  C Programs   /  C program to implement binary search

C program to implement binary search

#include<stdio.h> 
main()
{
int a[10],i,n,l,h,m,key; 
printf("enter the size of array: "); 
scanf("%d",&n);
printf("enter n elements into array: "); 
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the key element: "); 
scanf("%d",&key);
l=0;
h=n-1;
m = (l + h) / 2; 
while(l <= h)
{
if(a[m] < key){ 
  l=m+1;
}
else if(a[m]==key)
{
   printf("element found"); break;
}
else h=m-1;
m=(l+h)/2;
}
if(l > h)
{
printf("element not found");
}
}

 

Output:

 

C program to implement binary search

 

 

Leave a comment