Binary
Search is applicable only when the array is sorted. This method makes a
comparison between the ‘key’ (element to be searched) and middle element of
array.
Since
elements are sorted, comparisons may result in either a match or comp could be
continued with either left or right half of element. Left half element can be
selected by making ub=mid-1. Right half element, can be selected by making
ub=mid+1. The process of selecting either left half or right half continues
until the element is found or element is not there.
Ex.- Compare, if a[mid]==N number but 44 is greater than 30, Hence make lb=mid+1=3.
- Find mid=(lb+ub)/2=(3+4)/2=3 a[mid]=a[3]=44
- Compare, if (a[mid]==N) 44==44
Hence number is found in two comparison which is at 4th position, print it on screen.
Program:-
#include <stdio.h>
|
int main(void)
|
{
|
int i,key,a[12],n,flag=0;
|
int lb=0,mid,ub;
|
printf("\n how many element in array");
|
scanf("\n%d",&n);
|
ub=n-1;
|
printf("\n enter array element\n");
|
for(i=0;i<n;i++)
|
{
|
scanf("\n%d",&a[i]);
|
}
|
printf("\n enter the number to be search=");
|
scanf("\n%d",&key);
|
mid=(lb+ub)/2;
|
while(lb<=ub)
|
{
|
if(a[mid]==key)
|
{
|
flag=1;
|
break;
|
}
|
else if(key<mid)
|
ub=mid-1;
|
else
|
lb=mid+1;
|
mid=(lb+ub)/2;
|
}
|
if(flag==0)
|
printf("\n Number is not found");
|
else
|
printf("\n%d Number is found at location %d",key,mid+1);
|
return 0;
|
}
|
Please comment and give Suggestion on this post, if you want any other program or help then type in comment or contact me, and give feedback for this blogs.
No comments:
Post a Comment