You are on page 1of 2

PROGRAM NO.

: 1 LINEAR SEARCH AND BINARY SEARCH

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
struct std
{
int no;
char name[20];
float avg;
void input()
{
cout<<"\n Enter the Student number, Name and Average:";
cin>>no;
gets(name);
cin>>avg;
}

void output()
{
cout<<"\n Student Details";
cout<<"\n"<<no<<"\t"<<name<<"\t"<<avg;
}
}s[20];

int lin(struct std s[], char * data, int);


int bin(struct std s[], char * data, int);

void main()
{
clrscr();
int n;
char rep='y';
char *data;
cout<<"\n Enter the total number of students:";
cin>>n;
for(int i=0;i<n;i++)
s[i].input();
cout<<"\n Enter the name to be searched:";
gets(data);
int ch, f=0;
while(rep=='y')
{
cout<<"\n 1. Linear Search";
cout<<"\n 2. Binary Search";
cout<<"\n Enter the choice:";
cin>>ch;
switch(ch)
{
case 1:
f=lin(s,data,n);
break;
case 2:
f=bin(s,data,n);
break;
default:
cout<<"\n Invalid Choice";
}
if(f==0)
cout<<"\n Name n ot found";
else
cout<<"\n Name is found in the position:"<<f;
cout<<"\n Do you want to continue:";
cin>>rep;
}
getch();
}
int lin(struct std s[], char *item, int n)
{
int i;
for(i=0;i<n;i++)
{
if(strcmp(s[i].name,item)==0)
return(i+1);
}
return(0);
}
int bin(struct std s[], char * item,int n)
{
int mid,beg=0,last = n-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(strcmp(s[mid].name,item)==0)
return(mid+1);
else if(strcmp(s[mid].name,item)<0)
beg = mid + 1;
else if(strcmp(s[mid].name,item)>0)
last = mid -1;
}
return(0);
}

You might also like