Binary search is the most popular Search algorithm.It is efficient and also one of the most commonly used technique. it works only on a sorted set of elements.
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
File Name : bsearch.c
#include<stdio.h>
void main()
{
int n,i,l=0,h,m=0,f=0,sk,a[10];
printf("Enter number of elements: ");
scanf("%d",&n);
h=n-1;
printf("Enter %d integers :\n",n);
//Loop to store each numbers in array
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search value: ");
scanf("%d",&sk);
while(l<=h)
{
m=(l+h)/2;
if(sk==a[m])
{
f=1;break;
}
else if(sk<a[m])
h=m-1;
else
l=m+1;
}
if(f==1)
printf("%d Found at Index %d",sk,m);
else
printf("Search Key Not Found");
}
Output1:
Enter number of elements: 4
Enter 4 integers :
12
34
56
78
Enter the search value: 78
78 Found at Index 3
Output2:
Enter number of elements: 4
Enter 4 integers :
12
354
567
2345
Enter the search value: 5
Search Key Not Found
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
File Name : bsearch.c
#include<stdio.h>
void main()
{
int n,i,l=0,h,m=0,f=0,sk,a[10];
printf("Enter number of elements: ");
scanf("%d",&n);
h=n-1;
printf("Enter %d integers :\n",n);
//Loop to store each numbers in array
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the search value: ");
scanf("%d",&sk);
while(l<=h)
{
m=(l+h)/2;
if(sk==a[m])
{
f=1;break;
}
else if(sk<a[m])
h=m-1;
else
l=m+1;
}
if(f==1)
printf("%d Found at Index %d",sk,m);
else
printf("Search Key Not Found");
}
Output1:
Enter number of elements: 4
Enter 4 integers :
12
34
56
78
Enter the search value: 78
78 Found at Index 3
Output2:
Enter number of elements: 4
Enter 4 integers :
12
354
567
2345
Enter the search value: 5
Search Key Not Found
No comments:
Post a Comment