/* Binary Search */
#include<string.h>
#include<stdio.h>
void main()
{
int i,n,first,last,middle,search,a[10];
clrscr();
printf("\nEnter total number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d]:",i);
scanf("%d",&a[i]);
}
printf("\nEnter ele to search");
scanf("%d",&search);
first=0;
last=n-1;
while(first<=last)
{
middle=(first+last)/2;
if(a[middle]==search)
{
printf("%d found at %d",search,middle+1);
break;
}
else if(a[middle]>search)
{
last=middle-1;
}
else
{
first=middle+1;
}
}
if(first>last)
{
printf("Not found");
}
getch();
}
#include<string.h>
#include<stdio.h>
void main()
{
int i,n,first,last,middle,search,a[10];
clrscr();
printf("\nEnter total number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter a[%d]:",i);
scanf("%d",&a[i]);
}
printf("\nEnter ele to search");
scanf("%d",&search);
first=0;
last=n-1;
while(first<=last)
{
middle=(first+last)/2;
if(a[middle]==search)
{
printf("%d found at %d",search,middle+1);
break;
}
else if(a[middle]>search)
{
last=middle-1;
}
else
{
first=middle+1;
}
}
if(first>last)
{
printf("Not found");
}
getch();
}
No comments:
Post a Comment