Write a program to search a name using binary search.
#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char name[10][20], key[20];
int n, i, low, high, mid, found=0;
clrscr();
printf("Enter the number of names to read, n=");
scanf("%d", &n);
printf("Enter the names in ascending order\n");
for(i=0;i<n;i++)
scanf("%s", name[i]);
printf("Enter the name to be search:");
scanf("%s", key);
low=0;
high=n-1;
while(low<=high && !found)
{
mid=(low + high)/2;
if(strcmp(name[mid],key)==0)
found=1;
else if(strcmp(name[mid],key)<0)
low=mid+1;
else
high=mid-1;
}
if(found == 1)
printf("Name found in position : %d",mid+1);
else
printf("Name not found");
getch();
}
Output:
Enter the number of names to read, n= 5
Enter the names in ascending order
Amar
Chethan
Girish
Manoj
Yadu
Enter the name to be search:
Chethan
Name found in position :2
Post A Comment:
0 comments: