# include <stdio.h>
main()
{
int n,a[20],i,j,t=0,m,low=0,high,mid;
a[0]=0;
clrscr();
printf("\t\t\t\tBINARY SEARCH\n");
printf("\nEnter the no. of elements:\n");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(j=1;j<n;j++)
for(i=1;i<n;i++)
if (a[i]>a[i+1])
{
t=a[i];
a[i]=a[i+1];
a[i+1]=t;
}
printf("\nThe ordered list is...\n");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
printf("\n\nEnter the searching element:\n");
scanf("%d",&m);
high=n;
while(low<=high)
{
mid=(low+high)/2;
printf("\nMid element & position is... %d & %d",a[mid],mid);
switch(m<a[mid])
{
case 1:
high=mid-1;
break;
case 0: if(m==a[mid])
{
j=a[mid];
printf("\n\nThe element is present in the position %d.",mid);
break;
}
else
low=mid+1;
j=0;
}
if(j==m) break;
}
if(j==0)
printf("\n\nThe element is not present");
getch();
}
No comments:
Post a Comment