You are on page 1of 106

Clickhereforthebooksite

1of105

http://krishnarajpm.com

Program1
Write a C++ program to read series of names,
one per line, from standard input and write
these names spelled in reverse order to the
standardoutputusingI/Oredirectionandpipes.
Repeattheexerciseusinganinputfilespecified
by the user instead of the standard input and
using an output file specified by the user
insteadofthestandardoutput.
2of105

http://krishnarajpm.com

Program1
cout<<"Howmanynamesyouwanttoenter?";
cin>>count;
while(count)
{
cout<<"\nName:";
cin>>name;

Inputdata

rev.erase();
for(i=name.length();i>=0;i) Reversetheinput
rev+=name[i];
cout<<"\nReverse:"<<rev;
}

3of105

Output
http://krishnarajpm.com

Program1

NormalUsage

WithInputFile

./a.out<inputfile.txt

Thisshouldhavethecountalso
count

WithOutputFile

./a.out

./a.out>outputfile.txt

WithBothInputFileandOutputFile

4of105

./a.out<inputfile.txt>outputfile.txt

http://krishnarajpm.com

Program2
Write a C++ program to read and write student
objects with fixedlength records and the fields
delimitedby|.
Implement pack ( ), unpack ( ), modify ( ) and
search()methods.

5of105

http://krishnarajpm.com

Class
Definition

classstudent
{
public:
stringUSN;
stringName;
stringBranch;
intSemester;

stringbuffer;
voidpack();
voidunpack();
intsearch(string);
voidmodify(string);
voidread_data();
voidwrite_to_file();
intdelete_from_file(string);
}

6of105

http://krishnarajpm.com

Main
Program

7of105

case1:cout<<"\n\nhowmanyrecordstoinsert?\n";
cin>>count;
for(i=0;i<count;i++)
{
cout<<"Data\n";
s1.read_data();
s1.pack();
}
s1.write_to_file();
Writingmultiplerecordstofile
break;
case2:cout<<"\n\nEntertheUSNtodelete";
cin>>key;
i=s1.delete_from_file(key);
break;
case3:cout<<"\n\nEntertheUSNtomodify";
cin>>key;
s1.modify(key);
break;
case4:cout<<"\n\nEntertheUSNtosearch";
cin>>key;
i=s1.search(key);
break;
default:cout<<"\n\nWrongChoice";
http://krishnarajpm.com

voidstudent::read_data()
cout<<"\nUsn:";
cin>>USN;
cout<<"\nName:";
cin>>Name;
cout<<"\nBranch:";
cin>>Branch;
cout<<"\nSemster:";
cin>>Semester;

8of105

http://krishnarajpm.com

voidstudent::pack()
stringsem,temp;
stringstreamout;
out<<Semester;
sem=out.str();

Convertinginteger'Semestertostring'sem'

temp.erase();
temp+=USN+'|'+Name+'|'+Branch+'|'+sem;
for(;temp.size()<100;)temp+='$';
buffer+=temp+'\n';

9of105

Packthefields

Stuffittillreachesfixedsize(100)

Addthestuffedrecordtobuffer

http://krishnarajpm.com

voidstudent::write_to_file()

fstreamfile;
file.open("1.txt",ios::out|ios::app);
file<<buffer;
file.close();

10of105

http://krishnarajpm.com

voidstudent::unpack()

stringsem;
intch=1,i=0;
USN.erase();
while(buffer[i]!='|')
USN+=buffer[i++];
Name.erase();
i++;
while(buffer[i]!='|')
Name+=buffer[i++];
Branch.erase();
i++;
while(buffer[i]!='|')
Branch+=buffer[i++];

Convertingstring'semtointeger'Semester

11of105

sem.erase();
i++;
while(buffer[i]!='$')
sem+=buffer[i++];
istringstreamout(sem);
out>>Semester;

http://krishnarajpm.com

intstudent::search(stringkey)
ifstreamfile;
intflag=0,pos=0;
file.open("1.txt",ios::in);
while(!file.eof())
{
buffer.erase();
getline(file,buffer); ReadONErecordfromFILE
unpack();
if(key==USN)
{
pos=file.tellg(); ThelocationoftherecordinFILE
flag=1;
}
}
file.close();
if(flag)cout<<"FoundtheUSN.Therecordis"<<buffer;
elsecout<<"NotFound";
returnpos;
12of105

http://krishnarajpm.com

intstudent::delete_from_file(stringkey)
fstreamfile;
chardel_mark='*';
intpos=0,flag=0;
pos=search(key);
if(pos){
file.open("1.txt");
Rewindtobeginingoftherecord
pos=101;
file.seekp(pos,ios::beg);
file.put(del_mark);
flag=1;
}
file.close();
if(!flag)return0;
elsereturn1;
13of105

http://krishnarajpm.com

voidstudent::modify(stringkey)
intchoice;
if(delete_from_file(key)){

ReadthenewRecord

DeleteoldRecord

cout<<"\nWhattomodify?";
cin>>choice;
switch(choice)
{
case1:cout<<"\nUSN:";cin>>USN;break;
case2: cout<<"\nName:";cin>>Name;break;
case3: cout<<"\nBranch:";cin>>Branch;break;
case4: cout<<"\nSemster:";cin>>Semester;break;
default:cout<<"WrongChoice";
}
buffer.erase();
pack();
write_to_file();

14of105

InsertnewRecord
http://krishnarajpm.com

Program3
WriteaC++programtoreadandwritestudent
objectswithVariableLengthrecordsusingany
suitablerecordstructure.
Implementpack(),unpack(),modify()and
search()methods.

15of105

http://krishnarajpm.com

ImportthesefromProgram2
ClassDefinition
MainProgram
voidstudent::read_data()
voidstudent::write_to_file()
voidstudent::unpack()
intstudent::search(stringkey)
voidstudent::modify(stringkey)
16of105

http://krishnarajpm.com

voidstudent::pack()
FixedLengthRecord

VariableLengthRecord

stringsem,temp;
stringstreamout;
out<<Semester;
sem=out.str();
temp.erase();

stringsem;
stringstreamout;
out<<Semester;
sem=out.str();
buffer+=USN+'|'+Name+'|'+Branch+'|'+sem+'$'+'\n';

temp+=USN+'|'+Name+'|'+Branch+'|'+sem;
for(;temp.size()<100;)temp+='$';
buffer+=temp+'\n';

17of105

http://krishnarajpm.com

intstudent::delete_from_file(stringkey)
FixedLengthRecord
fstreamfile;
chardel_mark='*',t;
intpos,flag=0;
pos=search(key);
if(pos){
file.open("1.txt");
pos=101;
file.seekp(pos,ios::beg);
file.put(del_mark);
flag=1;
}
file.close();
if(!flag)return0;
elsereturn1;

18of105

VariableLengthRecord
fstreamfile;
chardel_mark='*',t;
intpos,flag=0;
pos=search(key);
if(pos){
file.open("1.txt");
pos=2;
t=file.get();
while(t!='$'&&pos!=0)
{pos;file.seekp(pos,ios::beg);t=file.get();}
if(pos!=0)file.seekp(pos+2,ios::beg);

elsefile.seekp(pos,ios::beg);
file.put(del_mark);
flag=1;
}
file.close();
if(!flag)return0;elsereturn1;

http://krishnarajpm.com

Program12
WriteaC++programtoreclaimthefreespace
resultingfromthedeletionofrecordsusing
linkedlists.

19of105

http://krishnarajpm.com

ClassDeclaration

classstudent
{
public:
stringUSN;
stringName;
stringBranch;
intSemester;

stringbuffer;
intavail[10];
inttop;
voidinitialize();
voidread_data();
voidpack();
voidwrite_to_file();
voidunpack();
intsearch(string);
intdelete_from_file(string);
voidmodify(string);
};

20of105

http://krishnarajpm.com

intstudent::delete_from_file(stringkey)
fstreamfile;
chardel_mark='*',t;
intpos,flag=0;
pos=search(key);
if(pos){
file.open("1.txt");
pos=101;//skipthe$$$$$$and\ncharacters
file.seekp(pos,ios::beg);
file.put(del_mark);
flag=1;
Addtheaddresstotheavaillist
avail[++top]=pos;
cout<<"\n\nThepositionofdeletedrecordis:"<<pos;
}
file.close();
buffer.empty();
if(!flag)return0;
elsereturn1;
21of105

http://krishnarajpm.com

voidstudent::write_to_file()
fstreamfile;
intpos;
file.open("1.txt");
Poptheavaillistandgetthepositiontoinsert
pos=avail[top];
if(pos){
file.seekp(pos,ios::beg);
file<<buffer;
Decrementtheavaillist
top;
cout<<"\n\nReusingDeletedSpaceatposition:"<<pos;
}
elsefile<<buffer;
file.close();

22of105

http://krishnarajpm.com

Program4
WriteaC++programtowritestudentobjectswith
VariableLengthrecordsusinganysuitable
fieldstructureandtoreadfromthisfilea
studentrecordusingRRN.

23of105

http://krishnarajpm.com

classstudent
{
public:
stringUSN;
stringName;
stringBranch;
intSemester;

ClassDeclaration

stringbuffer;
intcount;

TotalnumberofRecordsinthefile

intrrn_list[100];
voidread_data();
voidpack();
voidwrite_to_file();
voidunpack();

ImportfromProgram3

voidcreate_rrn();
voidsearch_by_rrn(int);
}
24of105

http://krishnarajpm.com

MainProgram

25of105

switch(choice)
{
case1:cout<<"Data\n";
s1.read_data();
s1.pack();
s1.write_to_file();
break;
case2:cout<<"\n\nEntertheRRN";
cin>>rrn;
s1.search_by_rrn(rrn);
break;
case3:return0;
default:cout<<"\n\nWrongChoice";
}

http://krishnarajpm.com

voidstudent::create_rrn()
ifstreamfile;
intpos;
count=1;
file.open("1.txt",ios::in);
while(!file.eof())
{
pos=file.tellg();
buffer.erase();
getline(file,buffer);
rrn_list[++count]=pos;
}
26of105

file.close();

http://krishnarajpm.com

voidstudent::search_by_rrn(intrrn)
fstreamfile;
if(rrn>count) cout<<"\nNotFound";
else{
buffer.erase();
file.open("1.txt");
pos=rrn_list[rrn];
file.seekp(pos,ios::beg);
getline(file,buffer);
cout<<"\n"<<buffer<<"\n";
}
27of105

http://krishnarajpm.com

Program5
WriteaC++programtoimplementsimpleindex
onprimarykeyforafileofstudentobjects.
Implementadd(),search(),delete()usingthe
index.

28of105

http://krishnarajpm.com

classprimary_index
{
public:
stringUSN_list[100];

ClassDeclaration

intAddress_list[100];
intcount;
voidcreate_primary_index();
voidinsert();
voidremove(string);
voidsearch(string);
intsearch_primary_index(string);
stringextract_USN(string);
voidsort_primary_index();
}

29of105

http://krishnarajpm.com

case1:cout<<"EntertheStudentdetails";
i1.insert();

MainProgram

break;
case2:cout<<"\n\nEntertheUSNtosearch";
cin>>key;
i1.search(key);
break;
case3:cout<<"\n\nEntertheUSNtodelete";
cin>>key;
i1.remove(key);
break;
case4:return0;
default:cout<<"\n\nWrongChoice";

30of105

http://krishnarajpm.com

fstreamfile;

create_primary_index()

intpos;
stringbuffer,USN;
count=1;

file.open("1.txt",ios::in);
while(!file.eof())
{
pos=file.tellg();
ReadONERecord

buffer.erase();
getline(file,buffer);
if(buffer.empty())break;

USN=extract_USN(buffer);
USN_list[++count]=USN;

InsertintoIndex

Address_list[count]=pos;
}
file.close();
sort_primary_index();
31of105

SortIndex???

http://krishnarajpm.com

stringprimary_index::extract_USN(stringbuffer)
stringUSN;
inti=0;
USN.erase();
while(buffer[i]!='|')
USN+=buffer[i++];
returnUSN;

32of105

http://krishnarajpm.com

voidprimary_index::sort_primary_index()
for(inti=0;i<=count;i++)
{
for(intj=i+1;j<=count;j++)
{
if(USN_list[i]>USN_list[j])
{
temp_USN=USN_list[i];
USN_list[i]=USN_list[j];
USN_list[j]=temp_USN;

temp_Address=Address_list[i];
Address_list[i]=Address_list[j];
Address_list[j]=temp_Address;
}}}

33of105

http://krishnarajpm.com

voidprimary_index::insert()
cin>>USN;cin>>Name;cin>Branch;cin>>Semester;
stringstreamout; out<<Semester;sem=out.str();

Readstudentdata

buffer.erase();
buffer=USN+'|'+Name+'|'+Branch+'|'+sem+'$'+'\n';

Pack

file.open("1.txt",ios::out|ios::app);
pos=file.tellp();
file<<buffer;
file.close();

Insertintofile

USN_list[++count]=USN;
Address_list[count]=pos;

AddtoIndex

sort_primary_index();

SortIndex

34of105

http://krishnarajpm.com

voidprimary_index::search(stringkey)
intpos=0,address;
stringbuffer;
fstreamfile;
buffer.erase();
pos=search_primary_index(key);
if(pos){
file.open("1.txt");
address=Address_list[pos];
file.seekp(address,ios::beg);
getline(file,buffer);
cout<<"FoundRecord:"<<buffer;
file.close();
}
elsecout<<"\nNotFound";
35of105

intprimary_index::
search_primary_index(stringkey)
intlow=0,high=count,mid=0,flag=0,pos;
while(low<=high)
{
mid=(low+high)/2;
if(USN_list[mid]==key){flag=1;break;}
if(USN_list[mid]>key)high=mid1;
if(USN_list[mid]<key)low=mid+1;
}
if(flag)returnmid;
elsereturn0;

http://krishnarajpm.com

voidprimary_index
::remove(stringkey)

intpos=0,address,i;
chardel_ch='*';
fstreamfile;

Searchfortherequiredrecord pos=search_primary_index(key);

Deletetherecordfromfile

if(pos){
address=Address_list[pos];
file.open("1.txt");
file.seekp(address,ios::beg);
file.put(del_ch);
file.close();
cout<<"\nRecordDeleted:";

DeletetherecordfromIndexlist

for(i=pos;i<count;i++)
{
USN_list[i]=USN_list[i+1];
Address_list[i]=Address_list[i+1];
}
count;
}
elsecout<<"\nNotFound";

36of105

http://krishnarajpm.com

Program6
WriteaC++programtoimplementindexon
secondarykey,thename,forafileofstudent
objects.Implementadd(),search(),delete()
usingthesecondaryindex.

37of105

http://krishnarajpm.com

ClassDeclaration

classsecondary_index
{
public:
stringName_list[100];
intAddress_list[100];
intcount;
voidcreate_index();
voidinsert();
voidremove(string);
voiddelete_from_file(int);
voidsearch(string);
intsearch_index(string);
voidread_from_file(int);
stringextract_Name(string);
voidsort_index();
};

38of105

http://krishnarajpm.com

MainProgram

case1:cout<<"EnterStudentDetails\n";
i1.insert();
break;
case2:cout<<"\n\nEnterthenametosearch";
cin>>key;
i1.search(key);
break;
case3:cout<<"\n\nEnterthenametodelete";
cin>>key;
i1.remove(key);
break;
case4:return0;
default:cout<<"\n\nWrongChoice";

39of105

http://krishnarajpm.com

voidsecondary_index::create_index()
fstreamfile;
intpos;
stringbuffer,Name;
count=1;
file.open("1.txt",ios::in);
while(!file.eof())
{
pos=file.tellg();
buffer.erase();
getline(file,buffer);
if(buffer.empty())break;
Name=extract_Name(buffer);
Name_list[++count]=Name;
Address_list[count]=pos;
}
file.close();
sort_index();

40of105

http://krishnarajpm.com

stringsecondary_index::extract_Name(stringbuffer)
stringUSN,Name;
inti=0;
USN.erase();
while(buffer[i]!='|')
USN+=buffer[i++];
Name.erase();
i++;
while(buffer[i]!='|')
Name+=buffer[i++];
returnName;

41of105

http://krishnarajpm.com

voidsecondary_index::sort_index()
for(inti=0;i<=count;i++)
{
for(intj=i+1;j<=count;j++)
{
if(Name_list[i]>Name_list[j])
{
temp_Name=Name_list[i];
Name_list[i]=Name_list[j];
Name_list[j]=temp_Name;

temp_Address=Address_list[i];
Address_list[i]=Address_list[j];
Address_list[j]=temp_Address;
}}}

42of105

http://krishnarajpm.com

voidsecondary_index::insert()
cin>>USN;cin>>Name;cin>Branch;cin>>Semester;
stringstreamout; out<<Semester;sem=out.str();
buffer.erase();
buffer=USN+'|'+Name+'|'+Branch+'|'+sem+'$'+'\n';
file.open("1.txt",ios::out|ios::app);
pos=file.tellp();
file<<buffer;
file.close();
Name_list[++count]=Name;
Address_list[count]=pos;
sort_primary_index();
43of105

http://krishnarajpm.com

voidsecondary_index::
search(stringkey)
pos=search_index(key);
if(pos){

while(low<=high)
{
mid=(low+high)/2;
if(Name_list[mid]==key){flag=1;break;}
if(Name_list[mid]>key)high=mid1;
if(Name_list[mid]<key)low=mid+1;
}
if(flag)returnmid;
elsereturn0;

read_from_file(pos);
t=pos;
while(Name_list[++t]==key)
read_from_file(t);
t=pos;
while(Name_list[t]==key)
read_from_file(t);
}
elsecout<<"\nNotFound";
44of105

address=Address_list[pos];
file.open("1.txt");
file.seekp(address,ios::beg);
getline(file,buffer);
file.close();
cout<<"\nFoundtherecord:"<<buffer;

http://krishnarajpm.com

voidsecondary_index::
remove(stringkey)

fstreamfile;
file.open("1.txt");
address=Address_list[pos];
file.seekp(address,ios::beg);
getline(file,buffer);
cout<<"\nFoundtherecord:"<<buffer;
file.close();

pos=search_index(key);
if(pos){
read_from_file(pos);
cout<<"\nDelete?";
cin>>choice;
if(choice)delete_from_file(pos);
file.open("1.txt");
t=pos;
address=Address_list[pos];
while(Name_list[++t]==key){
file.seekp(address,ios::beg);
read_from_file(t);
file.put(del_ch);
cout<<"\nDelete?";
cout<<"\nRecordDeleted:";
cin>>choice;
if(choice)delete_from_file(t);
for(i=pos;i<count;i++)
}t=pos;
{
while(Name_list[t]==key){
Name_list[i]=Name_list[i+1];
read_from_file(t);
Address_list[i]=Address_list[i+1];
cout<<"\nDelete?";
}
cin>>choice;
count;
if(choice)delete_from_file(t);
}}
elsecout<<"\nNotFound";
http://krishnarajpm.com
45of105

Program7
WriteaC++programtoreadtwolistsofnames
andthenmatchthenamesinthetwolistsusing
CosequentialMatchbasedonasingleloop.
Outputthenamescommontoboththelists.

46of105

http://krishnarajpm.com

ClassDeclaration
classcoseq
{
public:
stringlist1[100],list2[100];
intcount1,count2;
voidload_list();
voidsort_list();
voidmatch();
};

47of105

http://krishnarajpm.com

MainProgram
intmain()
{
coseqc1;
c1.load_list();
c1.sort_list();
c1.match();
return0;
}

48of105

http://krishnarajpm.com

voidcoseq::load_list()

fstreamfile;
stringname;
count1=1;count2=1;
file.open("name1.txt");
while(!file.eof()){
name.erase();
getline(file,name);
list1[++count1]=name;
}
file.close();
file.open("name2.txt");
while(!file.eof()){
name.erase();
getline(file,name);
list2[++count2]=name;
}
file.close();

49of105

http://krishnarajpm.com

voidcoseq::sort_list()

inti,j;
stringtemp;
for(i=0;i<=count1;i++)
{
for(j=i+1;j<=count1;j++)
{
if(list1[i]>list1[j])
{
temp=list1[i];
list1[i]=list1[j];
list1[j]=temp;
}}}
for(i=0;i<=count2;i++)
{
for(j=i+1;j<=count2;j++)
{
if(list2[i]>list2[j])
{
temp=list2[i];
list2[i]=list2[j];
list2[j]=temp;
}}}

50of105

http://krishnarajpm.com

voidcoseq::match()
inti=0,j=0;
while(i<=count1&&j<=count2)
{
if(list1[i]==list2[j]){cout<<"\n"<<list1[i];i++;j++;}
if(list1[i]<list2[j])i++;
if(list1[i]>list2[j])j++;
}

51of105

http://krishnarajpm.com

Program8
WriteaC++programtoreadkListsofnames
andmergethemusingkwaymergealgorithm
withk=8

52of105

http://krishnarajpm.com

ClassDeclaration
classcoseq
{
public:
stringlist[8][100];
stringoutlist[100];
intcount[8];
intcurrent[8];
voidload_list();
voidread_file(int);
voidsort_list(int);
voidmerge();
};

53of105

http://krishnarajpm.com

MainProgram
coseqc1;
c1.load_list();
c1.merge();
return0;

54of105

http://krishnarajpm.com

voidcoseq::load_list()
for(inti=1;i<=8;i++)
{
count[i]=1;
read_file(i);
sort_list(i);
}
inti,j;
stringtemp;
for(i=0;i<=count[k];i++)
{for(j=i+1;j<=count[k];j++)
{if(list[k][i]>list[k][j])
{
temp=list[k][i];
list[k][i]=list[k][j];
list[k][j]=temp;
55of105
}}}

fstreamfile;
stringname;
switch(i){
case1:file.open("name1.txt");break;
case2:file.open("name2.txt");break;
case3:file.open("name3.txt");break;
case4:file.open("name4.txt");break;
case5:file.open("name5.txt");break;
case6:file.open("name6.txt");break;
case7:file.open("name7.txt");break;
case8:file.open("name8.txt");break;
}
while(!file.eof()){
name.erase();
getline(file,name);
list[i][++count[i]]=name;
}
file.close();

http://krishnarajpm.com

voidcoseq::merge()1
stringsmallest;
intsmall_list,t=1,start=1,avail[8],avail_lists=8;
for(inti=1;i<=8;i++){avail[i]=1;current[i]=1;}
while(avail_lists>1)
{
if(!avail[start]){start++;continue;}
small_list=start;
smallest=list[start][current[start]];
for(inti=start+1;i<=7;i++)
{
if(!avail[i])continue;
if(list[i][current[i]]<smallest)
{
smallest=list[i][current[i]];
small_list=i;
}

ContinueuntilONElistremains
Ifcurrentlistisempty,ignoreit
Considerthecurrentelementassmallest

Ifcurrentelementofcurrentlistissmaller,
swapthem

}
56of105

http://krishnarajpm.com

voidcoseq::merge()2
current[small_list]++;
if(current[small_list]>count[small_list])
{
avail[small_list]=0;avail_lists;
}

Ifcurrentsmallestelementisthelast
elementinthelist,makethelist
unavailableforfutureuse

outlist[++t]=smallest;

Sendsmallestelementtooutlist

for(intj=1;j<=8;j++)
if(j!=small_list){
if(list[j][current[j]]==smallest){
current[j]++;}}
}

57of105

Ifanylisthastheelementsameas
smallestelement,incrementthem

http://krishnarajpm.com

voidcoseq::merge()3
for(inti=1;i<=8;i++)if(avail[i]){
for(intj=current[i];j<=count[i];j++)
outlist[++t]=list[i][j];}

Sendtheremainingelementsofthelists
tooutlist

cout<<"\nTheMergedList:";
for(inti=0;i<=t+1;i++)cout<<"\n"<<outlist[i];

58of105

http://krishnarajpm.com

Program9
WriteaC++programtoimplementBTreefora
givensetofintegersanditsoperationsinsert()
andsearch().Displaythetree.

59of105

http://krishnarajpm.com

ClassDefinition
structnode
{
intele[4];
intchild[4];
};

classbtree
{
public:
node*tree[10][10];
intcount[10];
intleaf;
intpath[10];
btree();
node*create_node();
voidinsert(int);
voidmain_search(int);
voiddisplay_tree();
voidinsert_node(node*,int);
voidsearch(int);
intsearch_node(node*,int);
intnodefull(node*);
voidsplit(node*);
};

60of105

http://krishnarajpm.com

MainProgram
while(1)
{
cout<<"\n\n\nMainMenu\n\n1.Insert\n2.Search\n3.Display
Tree\n4.Exit\n\nEnteryourchoice:";
cin>>choice;
switch(choice)
{
case1: cout<<"\nEntertheelement:";
cin>>key;
bt.insert(key);
break;
case2:cout<<"Enterthekey:";
cin>>key;
bt.main_search(key);
break;
case3:bt.display_tree();
break;
case4:return0;
default:cout<<"\nEntervalidchoice";
}
}
61of105

http://krishnarajpm.com

btree::btree()
leaf=1;
for(inti=0;i<10;i++)
{count[i]=1;path[i]=1;}

62of105

http://krishnarajpm.com

node*btree::create_node()
node*n;
n=newnode;
for(inti=0;i<4;i++){n>ele[i]=1;n>child[i]=1;}
returnn;

63of105

http://krishnarajpm.com

voidbtree::insert(intkey)1
intn,parent;
node*first_node;
if(leaf==1)
{
first_node=create_node();
tree[0][0]=first_node;
leaf++;count[0]++;
first_node>ele[0]=key;
}

64of105

http://krishnarajpm.com

voidbtree::insert(intkey)2
elseif(leaf==0)
{
if(nodefull(tree[0][0]))
{
path[leaf]=0;
split(tree[0][0]);
insert(key);
}
elseinsert_node(tree[0][0],key);
}

65of105

http://krishnarajpm.com

voidbtree::insert(intkey)3
else{
search(key);
n=path[leaf];
parent=path[leaf1];
if((nodefull(tree[leaf][n])))
{
split(tree[leaf][n]);
insert(key);
}
else
insert_node(tree[leaf][n],key);
}

66of105

http://krishnarajpm.com

voidbtree::main_search(intkey)
intflag=0,i;
node*node1;
search(key);
node1=tree[leaf][path[leaf]];
for(i=0;node1>ele[i]!=1;i++)
if(node1>ele[i]==key){flag=1;break;}
cout<<"\nThepathtraversedis:";
for(i=0;path[i]!=1;i++)
cout<<path[i]<<">";
if(flag)cout<<"\nElementFound";
elsecout<<"\nNotFound";

67of105

http://krishnarajpm.com

voidbtree::display_tree()
inti,j,k;
for(i=0;i<=leaf;i++)
{
cout<<"\n\nLevel"<<i<<"\n";
for(j=0;j<=count[i];j++)
{
for(k=0;tree[i][j]>ele[k]!=1;k++)
cout<<""<<tree[i][j]>ele[k];
cout<<"\t";
}
}

68of105

http://krishnarajpm.com

voidbtree::search(intkey)
inti,j,temp;
path[0]=0;
if(leaf){

69of105

alwaysstartthepathfromroot
searchonlyiftherearemorethan1level

j=0;
for(i=0;i<leaf;i++)
{
temp=search_node(tree[i][j],key);
path[i+1]=temp;
j=temp;
}}

http://krishnarajpm.com

intbtree::search_node(node*node1,intkey)
for(inti=0;i<4;i++)
{
if(key<=node1>ele[i])returnnode1>child[i];
elseif(node1>ele[i+1]==1)returnnode1>child[i];
}

70of105

http://krishnarajpm.com

intbtree::nodefull(node*node1)
if(node1>ele[3]!=1)return1;
elsereturn0;

71of105

http://krishnarajpm.com

voidbtree::insert_node(node*node1,intkey)1

intflag=0,count=1,i,j,x,y,l;
node*newnode,*parent;
for(i=0;i<4;i++)if(node1>ele[i]!=1)++count;
i=0;
while(!flag&&node1>ele[i]!=1)
{
if(node1>ele[i]>key)
{
flag=1;
for(intj=count;j>=i;j)
node1>ele[j+1]=node1>ele[j];
node1>ele[i]=key;
}
i++;
}

72of105

http://krishnarajpm.com

notconsideringduplicateentries

voidbtree::insert_node(node*node1,intkey)2

if(!flag)
{

73of105

ifhighestelementaddedatend,updateparent
node1>ele[count+1]=key;
for(i=leaf1;i>=0;i)
{
n1=tree[i][path[i]];
for(t=0;n1>ele[t]!=1;t++);
n1>ele[t1]=key;
}

http://krishnarajpm.com

voidbtree::split(node*oldnode)1

node*newnode,*parent,*n1,*n2;
inti,j,k,n,t,x,y,pos;
newnode=create_node();

createnewnode

newnode>ele[0]=oldnode>ele[2];
newnode>ele[1]=oldnode>ele[3];

copyelementstonewnode

oldnode>ele[2]=1;
oldnode>ele[3]=1;

deleteentriesinoldnode

t=count[leaf];
n=path[leaf];
for(i=t,j=t+1;i>n;i,j)
tree[leaf][j]=tree[leaf][i];
74of105

movetheelementsinleafleveloneplaceright
http://krishnarajpm.com

voidbtree::split(node*oldnode)2
tree[leaf][n+1]=newnode;
count[leaf]++;

insertnewnodetothetree
incresethecountofleaflevelnodes

x=leaf;
if(count[leaf]+1==1)t=1;elset=log(count[leaf]+1)/log(2);
howmanylevelsdoesthetreeneed?
if(t!=leaf)
{
++leaf;
count[leaf]=count[x];

increasethelevelofthetree

for(i=0;i<=count[leaf];i++)
std::swap(tree[leaf][i],tree[x][i]);

copytheleafnodestothenewlevel

}
for(i=leaf1;i>=0;i)count[i]=1;
75of105

emptythetree

http://krishnarajpm.com

voidbtree::split(node*oldnode)3
for(i=t,j=i1;i>0;i,j)
createtheparentnodes
{
for(k=0;k<(count[i]+1)/2;k++)
{
n1=tree[i][2*k];
n2=tree[i][(2*k)+1];
for(x=0;n1>ele[x]!=1;x++);
for(y=0;n2>ele[y]!=1;y++);

findlastelementinthenodes

newnode=create_node();
count[j]++;
tree[j][count[j]]=newnode;
newnode>ele[0]=n1>ele[x1];
newnode>child[0]=2*k;
newnode>ele[1]=n2>ele[y1];
newnode>child[1]=(2*k)+1;

copythemtonewparent

}
76of105

http://krishnarajpm.com

voidbtree::split(node*oldnode)4
if(count[i]!=1&&count[i]%2==0)
ifonenodeisremainingatleaf
{
copyitshighestelementto
{
parent
n2=tree[i][count[i]];
for(y=0;n2>ele[y]!=1;y++);
newnode>ele[2]=n2>ele[y1];
newnode>child[2]=count[i];
}
}

77of105

http://krishnarajpm.com

Program10
WriteaC++programtoimplementB+Treefora
givensetofintegersanditsoperationsinsert()
andsearch().Displaythetree.

78of105

http://krishnarajpm.com

ClassDeclaration

classbptree
{
public:
node*tree[10][10];
intcount[10];
intleaf;
intpath[10];
node*head;
bptree();
node*create_node();
voidinsert(int);
voidmain_search(int);
voiddisplay_tree();
voidinsert_node(node*,int);
voidsearch(int);
intsearch_node(node*,int);
intnodefull(node*);
voidsplit(node*);
voiddisplay_seqset();

structnode
{
intele[4];
intchild[4];
node*next;
};
};

79of105

http://krishnarajpm.com

MainProgram
while(1)
{
cout<<"\n\n\nMainMenu\n\n1.Insert\n2.Search\n3.Display
Tree\n4.DisplaySequenceSet\n5.Exit\n\nEnteryourchoice:";
cin>>choice;
switch(choice)
{
case1: cout<<"\nEntertheelement:";
cin>>key;
bt.insert(key);
break;
case2:cout<<"Enterthekey:";
cin>>key;
bt.main_search(key);
break;
case3:bt.display_tree();
break;
case4:bt.display_seqset();
break;
case5:return0;
default:cout<<"\nEntervalidchoice";
}
80of105

http://krishnarajpm.com

bptree::bptree()
leaf=1;
for(inti=0;i<10;i++)
{count[i]=1;path[i]=1;}

81of105

http://krishnarajpm.com

node*bptree::create_node()
node*n;
n=newnode;
for(inti=0;i<4;i++){n>ele[i]=1;n>child[i]=1;}
n>next=NULL;
returnn;

82of105

http://krishnarajpm.com

voidbptree::insert(intkey)
if(leaf==1)
{
first_node=create_node();
tree[0][0]=first_node;
leaf++;count[0]++;
first_node>ele[0]=key;
head=first_node;
}

83of105

http://krishnarajpm.com

headernodeofseqset

voidbptree::display_tree()
inti,j,k;
for(i=0;i<=leaf;i++)
{
cout<<"\n\nLevel"<<i<<"\n";
for(j=0;j<=count[i];j++)
{
if(i!=leaf)k=1;elsek=0;

printfirstelementonlyatleaflevel

for(;tree[i][j]>ele[k]!=1;k++)
cout<<""<<tree[i][j]>ele[k];
cout<<"\t";
}
}

84of105

http://krishnarajpm.com

voidbptree::display_seqset()
node*t;
intk;
t=head;
cout<<"\n\nThesequencesetis:";
while(t)
{
for(k=0;t>ele[k]!=1;k++)
cout<<""<<t>ele[k];
cout<<"\t";
t=t>next;
}

85of105

http://krishnarajpm.com

intbptree::search_node(node*node1,intkey)
if(key<=node1>ele[0])
returnnode1>child[0];

keylessthanfirstelementinnode

for(inti=1;i<4;i++)
{
if((key>=node1>ele[i])&&(key<node1>ele[i+1]))
returnnode1>child[i];
elseif(node1>ele[i+1]==1)
returnnode1>child[i];

keymorethanlastelementinnode

86of105

http://krishnarajpm.com

voidbptree::insert_node(node*node1,intkey)1

sameasbtree

87of105

intflag=0,count=1,i,j,x,y,l;
node*newnode,*parent;
for(i=0;i<4;i++)if(node1>ele[i]!=1)++count;
i=0;
while(!flag&&node1>ele[i]!=1)
{
if(node1>ele[i]>key)
notconsideringduplicateentries
{
flag=1;
for(intj=count;j>=i;j)
node1>ele[j+1]=node1>ele[j];
node1>ele[i]=key;
}
i++;
}
http://krishnarajpm.com

voidbptree::insert_node(node*node1,intkey)2

if(!flag) node1>ele[count+1]=key;
if(node1>ele[0]==key)
{

highestelementaddedatend

newelementisthelowest,hencepropogatethistillroot

for(i=leaf1;i>=0;i)
{
x=path[i+1];
if(tree[i][path[i]]>ele[x]>key)tree[i][path[i]]>ele[x]=key;
elseinsert_node(tree[i][x],key);
}

88of105

http://krishnarajpm.com

voidbptree::split(node*oldnode)1
(takenfrombtree)
node*newnode,*parent,*n1,*n2;
inti,j,k,n,t,x,y,pos;
newnode=create_node();

createnewnode

newnode>ele[0]=oldnode>ele[2];
newnode>ele[1]=oldnode>ele[3];

copyelementstonewnode

oldnode>ele[2]=1;
oldnode>ele[3]=1;

deleteentriesinoldnode

t=count[leaf];
n=path[leaf];
for(i=t,j=t+1;i>n;i,j)
tree[leaf][j]=tree[leaf][i];
89of105

movetheelementsinleafleveloneplaceright
http://krishnarajpm.com

additionaltasksforB+Trees
newnode>next=tree[leaf][n]>next;

updatingthenextpointers

tree[leaf][n]>next=newnode;

90of105

http://krishnarajpm.com

voidbptree::split(node*oldnode)2
(takenfrombtree)
tree[leaf][n+1]=newnode;
count[leaf]++;

insertnewnodetothetree
incresethecountofleaflevelnodes

x=leaf;
if(count[leaf]+1==1)t=1;elset=log(count[leaf]+1)/log(2);
howmanylevelsdoesthetreeneed?
if(t!=leaf)
{
++leaf;
count[leaf]=count[x];

increasethelevelofthetree

for(i=0;i<=count[leaf];i++)
std::swap(tree[leaf][i],tree[x][i]);

copytheleafnodestothenewlevel

}
for(i=leaf1;i>=0;i)count[i]=1;
91of105

emptythetree

http://krishnarajpm.com

voidbptree::split(node*oldnode)3
(takenfrombtree)
for(i=t,j=i1;i>0;i,j)
{
for(k=0;k<=count[i]/3;k++)
{
n1=tree[i][2*k];
n2=tree[i][(2*k)+1];

createtheparentnodes

for(x=0;n1>ele[x]!=1;x++);
for(y=0;n2>ele[y]!=1;y++);

findlastelementinthenodes

newnode=create_node();
count[j]++;
tree[j][count[j]]=newnode;
newnode>ele[0]=n1>ele[0];
newnode>child[0]=2*k;
newnode>ele[1]=n2>ele[0];
newnode>child[1]=(2*k)+1;

copyfirstelementstonewparent

}
92of105

http://krishnarajpm.com

voidbtree::split(node*oldnode)4
(takenfrombtree)
if(count[i]!=1&&count[i]%2==0)
{
{
n2=tree[i][count[i]];

ifonenodeisremainingatleaf
copyitshighestelementto
parent

for(y=0;n2>ele[y]!=1;y++);
newnode>ele[2]=n2>ele[0];

copythefirstelementtoparent

newnode>child[2]=count[i];
}
}

93of105

http://krishnarajpm.com

Program11
WriteaC++programtostoreandretrievestudent
datafromfileusinghashing.Useanycollision
resolutiontechnique.

94of105

http://krishnarajpm.com

ClassDeclaration

classstudent
{
public:
stringUSN;
stringName;
stringBranch;
intSemester;

stringbuffer;
voidread_data();
voidpack();
voidwrite_to_file();
voidunpack(int);
voidsearch(string);
inthash(string);
}

95of105

http://krishnarajpm.com

Main

while(1){
cout<<"\nMainMenu\n1.Add\n\n2.Search\n\n3.Exit\n\nEnterthechoice:";
cin>>choice;
switch(choice)
{
case1:cout<<"Data\n";
s1.read_data();
s1.pack();
s1.write_to_file();
break;

Program

case2:cout<<"\n\nEnterthekey";
cin>>key;
s1.search(key);
break;
case3:return0;
default:cout<<"\n\nWrongChoice";
}
96of105

http://krishnarajpm.com

intstudent::hash(stringkey)
intstudent::hash(stringkey)
{
intt;
t=(((key[7]48)*100)+((key[8]48)*10)+(key[9]48))%9;
if(t==0)return9elsereturnt;
}

97of105

Key

HashFunction

ReturnValue

1MS06IS001

001%9

1MS06IS029

029%9

1MS06IS135

135%9

9
http://krishnarajpm.com

voidstudent::read_data()
cout<<"\nUsn:";
cin>>USN;
cout<<"\nName:";
cin>>Name;
cout<<"\nBranch:";
cin>>Branch;
cout<<"\nSemster:";
cin>>Semester;

98of105

http://krishnarajpm.com

voidstudent::pack()
stringsem,temp;
stringstreamout;
out<<Semester;
sem=out.str();
buffer.erase();
temp.erase();
temp+=USN+'|'+Name+'|'+Branch+'|'+sem;
for(;temp.size()<100;)temp+='$';
buffer=temp+'\n';

99of105

http://krishnarajpm.com

voidstudent::write_to_file()1
fstreamfile;
stringtemp;
intcount,pos;
pos=hash(USN);
pos;
pos=pos*304;

Findthehashvalue
Findthepositiontoinsert

file.open("1.txt");
file.seekp(pos,ios::beg);
getline(file,temp);
file.close();
count=temp[0]48;

100of105

Howmanyrecordsarethereinthisaddress?

http://krishnarajpm.com

voidstudent::write_to_file()2
file.open("1.txt");
if(count<0)
{
file.seekp(pos,ios::beg);
file.put('1');
pos=pos+1;
}
elseif(count==1)
{
file.seekp(pos,ios::beg);
file.put('2');
pos=pos+102;
}
elseif(count==2)
{

Incrementthecountofrecords

file.seekp(pos,ios::beg);
file.put('3');
pos=pos+203;
}
101of105

http://krishnarajpm.com

voidstudent::write_to_file()3
cout<<"\nInsertingat:"<<pos;
file.seekp(pos,ios::beg);
file<<buffer;
file.close();

Inserttherecord

if(count==3)
cout<<"\n\nCannotInsert....Overflow";

102of105

http://krishnarajpm.com

stringsem;
intch=1,i=0;
USN.erase();
if(flag==1)i++;

skipthecountiftherearerecordsinthataddress

while(buffer[i]!='|')
USN+=buffer[i++];
Name.erase();
i++;
while(buffer[i]!='|')
Name+=buffer[i++];
Branch.erase();
i++;
while(buffer[i]!='|')
Branch+=buffer[i++];

voidstudent::unpack(intflag)

sem.erase();
i++;
while(buffer[i]!='$')
sem+=buffer[i++];
istringstreamout(sem);
out>>Semester;
103of105

http://krishnarajpm.com

voidstudent::search(stringkey)1
fstreamfile;
intflag=0,pos=0,count,i=1;
stringtemp;
pos=hash(key);
pos;
pos=pos*304;

Hashandfindtherequiredaddress

file.open("1.txt");
file.seekp(pos,ios::beg);
getline(file,temp);
count=temp[0]48;

104of105

Readthecount

http://krishnarajpm.com

voidstudent::search(stringkey)2
file.seekp(pos,ios::beg);
while(i<=count)
{
buffer.erase();
getline(file,buffer);
unpack(i++);
if(key==USN)flag=1;
}

Readeachrecordandcompare

if(!flag)cout<<"\n\nKeynotfound:";
else{
cout<<"\nTheRecorddetailsare";
cout<<USN<<Name<<Branch<<<<Semester;
}
file.close();
105of105

http://krishnarajpm.com

106of105

http://krishnarajpm.com

You might also like