Pages

Subscribe:

Blogger templates

Monday, February 4, 2013

BINARY SEACH

BINARY SEARCH


//PROGRAM FOR BINARY SEARCH
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct teacher
{
char name[20];
int tno;
float salary;
}obj[5];
void main()
{
clrscr();
int size;
cout<<"\nEnter the no. of records you want to enter (maximum 5):\n";
cin>>size;
for(int i=0;i<size;i++)
{
cout<<"\nEnter the details of "<<i+1<<" teacher-";
cout<<"\nEnter the name of "<<i+1<<" teacher-";
gets(obj[i].name);
cout<<"Enter the teacher id of the "<<i+1<<" teacher-";
cin>>obj[i].tno;
cout<<"Enter the salary of "<<i+1<<" teacher-";
cin>>obj[i].salary;
}
int no,beg=0,end=size-1;
char ch='y';
while(ch=='y')
{
cout<<"\nEnter the teacher id you want to search-";
cin>>no;
int mid;
while(beg<=end)
{
mid=(beg+end)/2;
if(obj[mid].tno==no)
{
cout<<"\nSEARCH IS SUCCESSFUL!!!";
cout<<"\nElement is found at "<<mid+1<<" position";
cout<<"\nThe details of "<<mid+1<<" teacher is:";
cout<<"\nThe name of "<<mid+1<<" teacher is "<<obj[mid].name;
cout<<"\nThe teacher id of the "<<mid+1<<" teacher is "<<obj[mid].tno;
cout<<"\nThe salary of "<<mid+1<<" teacher is"<<obj[mid].salary;
break;
}
else if(obj[mid].tno<no)
beg=mid+1;
else
end=mid-1;
}
if(beg>end)
cout<<"\nSEARCH IS UNSUCCESSFUL! Element could not be found";

cout<<"\n\nDo you want to search again (y/n):";
cin>>ch;
}
getch();
}



0 comments:

Post a Comment