Sie sind auf Seite 1von 73

Data Structure Through C++ Lab

Laboratory manual for

DATA STRUCTURES THROUGH C++


II B.Tech I Semester for CSE

Prepared By
B. Ashok Kumar M.Sc (Comp.Sc)

Turbomachinery Institute of Technology & Sciences 1 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Certificate
This is to certify that Mr. / Ms. ………………………………….. RollNo……………..

… of I/II/III/IV B.Tech I / II Semester of …………….……………………..…………branch has

completed the laboratory work satisfactorily in …………………..…….……..... Lab for the academic

year 20 … to 20 …as prescribed in the curriculum.

Place: …………….….

Date: ……………..….

Lab In charge Head of the Department Principal

Turbomachinery Institute of Technology & Sciences 2 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

INSTRUCTIONS TO STUDENTS
Students shall read the points given below for understanding the theoretical concepts and Practical applications.

1. Listen carefully to the lecture given by teacher about importance of subject, curriculum philosophy, Learning structure,

skills to be developed, information about equipment, instruments, procedure, method of continuous assessment, tentative

plan of work in Laboratory and total amount of work to be done in a semester

2. Students shall undergo study visit of the laboratory for types of equipment, instruments and

material to be used, before performing experiments.

3. Read the write up of each experiment to be performed, a day in advance.

4. Organize the work in the group and make a record of all observations.

5. Understand the purpose of experiment and its practical implications.

6. Student should not hesitate to ask any difficulty faced during conduct of practical / exercise.

7. Student shall develop maintenance skills as expected by the industries.

8. Student should develop the habit of pocket discussion / group discussion related to the experiments/ exercises so that

exchanges of knowledge / skills could take place.

9. Student should develop habit to submit the practical, exercise continuously and progressively on the scheduled dates

and should get the assessment done.

10. Student shall attempt to develop related hands - on - skills and gain confidence.

11. Student shall focus on development of skills rather than theoretical or codified knowledge.

12. Student shall visit the nearby workshops, workstation, industries, laboratories, technical exhibitions trade fair etc. even

not included in the Lab Manual. In short, students should have

exposure to the area of work right in the student hood.

13. Student shall develop the habit of evolving more ideas, innovations, skills etc. those included in the scope of the manual.

14. Student shall refer to technical magazines, proceedings of the Seminars, refer websites

related to the scope of the subjects and update their knowledge and skills.

15. The student shall study all the questions given in the laboratory manual and practice to write the answers to these

questions.

Turbomachinery Institute of Technology & Sciences 3 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

INDEX

Pag Date of Date of Assessmen


e Perform Submissio t of Marks Sign of
S.NO NAME OF THE EXERCISE
No ance n (10 Marks) Faculty

CYCLE - I
a) Stack ADT using arrays
Week
1 b) Queue ADT using
arrays
a) Stack ADT using single
linked lists
Week
2 b) Queue ADT using single
linked lists
Deque using stack
Week Deque using doubly linked
3 list
Binary Search Tree(BST)-
Operations
a) Insert an element into
BST
Week b) Delete an element from
4 a BST
C) Search for a
keyelement in a BST
Tree Traversals using
Recursive Functions
a) Preorder
Week
b) Inorder
5
c) Postorder
Tree Traversals using
Non-Recursive Functions
Week
a) Preorder
6
b) Inorder
c) Postorder
CYCLE - II
Graph-DFS
Week
Graph-BFS
7
Week Merge sort
8 Heap Sort
B-Tree Operations
Week
9 a) Insertion into a B -tree
b) Deletion from a B-tree
Week a)Insertion into an AVL
10 Tree
Week Dictionary ADT using
11 hashing
Week Knuth – Morris- Pratt
12 Algorithm

Turbomachinery Institute of Technology & Sciences 4 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 1. a) Write a C++ program to implement stack ADT using arrays.

AIM:
To write a C++ program to implement stack ADT using arrays.

ALGORITHM:

1. Push ( )

1. start
2. read n
3. if top greater than (n-1) then
4. print “overflow”
5. else
6. top top+1
7. data[top]=d
8. print “element pushed to stack”
9. stop.

2. Pop( )

1. start
2. if top< 0 then
3. print “underflow”
4. else
5. d data[top]
6. top top-1
7. print “element is popped from the stack”
8. stop.

PROGRAM:

#include <iostream.h>
#include <conio.h>
#define size 15
template <class T>
class stack
{
T top,stk[size];
public:
stack();
void push(T n);
T pop();
};
template<class T> stack<T>::stack()
{
top=0;
}
template<class T> void stack<T>::push(T n)
{
if (top==size)
{cout<<"\n stack is full";

Turbomachinery Institute of Technology & Sciences 5 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

}
stk[top]=n;
top++;
}
template<class T> stack<T>::pop()
{
if(top==NULL)
{
cout<<"\n stack is empty\n";
}
top--;
return(stk[top]);
}
void main()
{
stack <int> ob;
int i=0;
clrscr();
cout<<"elements of stack"<<endl;
for(i=0;i<size;i++)
{
ob.push(i);
cout<<"\n pushed element "<<i;
}
cout<<endl;
cout<<"elements out of stack"<<endl;
for(i=0;i<5;i++)
{cout<<"\npopped out element is "<<ob.pop();
}
getch();
}

OUTPUT:
elements of stack
pushed element 0
pushed element 1
pushed element 2
pushed element 3
pushed element 4
pushed element 5
pushed element 6
pushed element 7
pushed element 8
pushed element 9
pushed element 10
pushed element 11
pushed element 12
pushed element 13
pushed element 14
elements out of stack
popped out element is 14
popped out element is 13
popped out element is 12
popped out element is 11
popped out element is 10

Turbomachinery Institute of Technology & Sciences 6 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

b) Write a C++ program to implement queue ADT using arrays.

AIM:
To write a C++ program to implement queue ADT using arrays.

ALGORITHM:

1. Insertion( )

1. start
2. read n
3. if rear== (n-1) then
4. print “overflow”
5. print “enter a number”
6. read num
7. if front == -1 then
8. front=rear=0
9. else
10.rear=rear+1
11.a[rear]=num
12.print”number is inserted”
13.stop

2. Deletion( )

1. start
2. if front == -1 then
3. print “underflow”
4. print “deleted element is”
5. print a[front]
6. if front==rear then
7. front=rear=-1
8. else
9. front=front+1
10.print “number is deleted”
11.stop.

PROGRAM:

#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
const int size=10;
int rear=-1,front=0;
template<class T>
class queue
{

Turbomachinery Institute of Technology & Sciences 7 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

T qa[size];
T temp;
public:
int empty(void);
int full(void);
void insert(T x);
T delet(void);
void disp();
};
template<class T>
int queue<T>::empty(void)
{
if(front>rear)
return(0);
else
return 1;
}
template<class T>
int queue<T>::full(void)
{
if(rear>size-1)
return 0;
else
return 1;
}
template<class T>
void queue<T>::insert(T x)
{
qa[++rear]=x;
cout<<endl;
}
template<class T>
T queue<T>::delet()
{
return (qa[front++]);
}
template<class T>
void queue<T>::disp()
{
if(front>rear)
cout<<"queue is empty"<<endl;
else
{for(int i=rear;i>=front;i--)
cout<<qa[i];
}
}
void main()
{
int p;
int v;
queue<int> q;
clrscr();
q.empty();
q.full();
q.insert(5);

Turbomachinery Institute of Technology & Sciences 8 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

q.delet();
q.disp();
getch();
}

OUTPUT:

*************MENU************
1.Insert
2.Delete
3.Display
4.Quit
Enter Ur Choice
1
Enter size
3
Enter elements
12
13
14

*************MENU************
1.Insert
2.Delete
3.Display
4.Quit
Enter Ur Choice
2
12 13 14
*************MENU************
1.Insert
2.Delete
3.Display
4.Quit
Enter Ur Choice
3

deleted element is
12
*************MENU************
1.Insert
2.Delete
3.Display
4.Quit
Enter Ur Choice
3

deleted element is
13

Turbomachinery Institute of Technology & Sciences 9 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 2.a) Write a C++ Program to implement a Stack ADT using a


singly linked list

AIM:
To write a C++ program to implement a Stack ADT using a singly
linked list.

ALGORITHM:

1. Push (d)

1. start
2. *n is a new node
3. read num
4. n d = num
5. n  next = top
6. top=n
7. print num
8. print “is pushed to stack”
9. stop.

2. Pop ( )

1. start
2. if top == NULL then
3. print “underflow”
4. num= top d
5. *d is the new node
6. d=top
7. top=top next
8. deleted
9. stop.

PROGRAM:

#include <iostream.h>
#include <conio.h>
#include <process.h>
class stak
{
struct stks
{ int data;
stks *next;
};
stks *p,*temp,*top;
public:
stak()
{ top = NULL; }
push();
pop();
disp();
};

Turbomachinery Institute of Technology & Sciences 10 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

stak::push()
{ clrscr();
temp= new stks;
cout<<"enter a value \n";
cin>>temp->data;
if(top==NULL)
{
top = temp;
temp->next=NULL;
}
else
{ temp->next=top;
top=temp;
}
cout<<"the element inserted = "<<temp->data<<endl;
getch();
return 0;
}
stak::pop()
{
clrscr();
p=top;
if(top==NULL)
cout<<"stack is empty\n";
else
{
top = top->next;
cout<<"element iremoved = "<<p->data;
delete p;
} return 0;}
stak::disp()
{ if(top==NULL)
cout<<"stack is empty\n";
else
{
p=top;
cout<<"stack contains \n";
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
} }return 0; }
void main()
{
stak s1;
int ch,l;
clrscr();
cout<< "stack operations using Linked list\n";
while(l)
{
cout<<"\n 1. PUSH\n";
cout<<"2.POP\n";
cout<<"3.DISPLAY\n";
cout<<"4.quit\n";
cout<<"enter Ur choice\n";

Turbomachinery Institute of Technology & Sciences 11 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

cin>>ch;
switch(ch)
{
case 1: s1.push();
break;
case 2: s1.pop();
break;
case 3: s1.disp();
break;
default: exit(0);
}}}

OUTPUT:
stack operations using Linked list
1. PUSH
2.POP
3.DISPLAY
4.quit
enter Ur choice
1
enter a value
12
the element inserted = 12
1. PUSH
2.POP
3.DISPLAY
4.quit
enter Ur choice
1
enter a value
13
the element inserted = 13
1. PUSH
2.POP
3.DISPLAY
4.quit
enter Ur choice
3
stack contains
13 12
1. PUSH
2.POP
3.DISPLAY
4.quit
enter Ur choice
2
element iremoved = 13
1. PUSH
2.POP
3.DISPLAY
4.quit
enter Ur choice 2

Turbomachinery Institute of Technology & Sciences 12 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

b) Write a C++ program to implement a queue ADT using a singly


linked list.

AIM:
To write a C++ program to implement a queue ADT using a singly
linked list.

ALGORITHM:

1. Insertion ( )

..1.1.start
..1.2.*link is a new node
..1.3.read num
..1.4.*new is a new node
..1.5.n data=num //storing the data
..1.6.n link = NULL //storing the address
..1.7.If front == NULL then
..1.7.1 Front = rear=n
..1.7.2 Print “number is inserted”
..1.7.3 Return
..1.8.rear link =n
..1.9.rear=n
..1.10.print “number is inserted”

2. Deletion ( )

.1start
.2*d is a new node
.3if front == NULL then
.1 print “underflow”
.2 return
.4if front is equal to rear then
.1 front = rear = NULL
.2 print “ no. is deleted”
.3 return
.5d=front
.6front=front link
.7print d data
.8print “is deleted”
.9deleted
.10stop.

PROGRAM:

#include <iostream.h>
#include <conio.h>
#include <stdlib.h>

class rque
{
struct node
{

Turbomachinery Institute of Technology & Sciences 13 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

int data;
node *link;
}*fr,*re;
public:
rque();
void addq(int item);
int delq();
void disp();
// ~rque();
};
rque::rque()
{
fr=re=NULL;
}
void rque::addq(int item)
{
node *temp;
temp=new node;
if(temp==NULL)
cout<<"Queue is full\n";
temp->data=item;
temp->link=NULL;
if(fr==NULL)
{
re=fr=temp;
return;
}
re->link=temp;
re=re->link;
}
int rque::delq()
{
if(fr==NULL)
{
cout<<"\nQueue is empty\n";
return NULL;
}
else
{node *temp;
int item;
item=fr->data;
temp=fr;
fr=fr->link;
delete temp;
return item;}
}
/* rque::~rque()
{
if(fr==NULL)
return;
node *temp;
while(fr!=NULL)
{
temp=fr;
fr=fr->link;

Turbomachinery Institute of Technology & Sciences 14 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

delete temp;
}
} */
void rque::disp()
{
while(fr!=NULL)
{cout<<fr->data<<"\n";
fr=fr->link;
} }
void main()
{
rque rq;
int i,size,a[10],ch=1;
clrscr();
while(ch!=5)
{
cout<<"\n *************MENU***********\n";
cout<<" 1.Insert\n";
cout<<" 2.Display\n";
cout<<" 3.Delete\n";
cout<<" 4.Quit\n";
cout<<"Enter Ur Choice\n";
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"\n enter the size of the queue\n";
cin>>size;
cout<<"Enter elements\n";
for(i=0;i<size;i++)
{ cin>>a[i];
rq.addq(a[i]);
} break;
}
case 2:
{
cout<<"Display list\n";
rq.disp();break;
}
case 3:
{
cout<<"Delete process\n";
int j=rq.delq();
cout<<"Extracted element is "<<j;
break;
}
case 4: {
exit(1);
break; }
}}
getch();
}

Turbomachinery Institute of Technology & Sciences 15 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

OUTPUT:

*************MENU***********
1.Insert
2.Display
3.Delete
4.Quit
Enter Ur Choice
1

enter the size of the queue


4
Enter elements
12
13
14
15

*************MENU***********
1.Insert
2.Display
3.Delete
4.Quit
Enter Ur Choice
2
Display list
12
13
14
15

*************MENU***********
1.Insert
2.Display
3.Delete
4.Quit
Enter Ur Choice
3
Delete process

Queue is empty
Extracted element is 0
*************MENU***********
1.Insert
2.Display
3.Delete
4.Quit
Enter Ur Choice

Turbomachinery Institute of Technology & Sciences 16 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 3.a) Write a C++ program to implement the deque( doubly


ended queue ) ADT using a stack.

AIM:
To write a c++ program to implement deque ADT using a stack.

ALGORITHM:

1.Insertion_Front()

1. start
2. if front == 0 & rear==-1
a. d[front]==x
b. rear++
3. if front == 0 & rear != -1
a. print “insertion not possible”
4. else
a. f--
b. dq[f]=x
5. print “ no. is inserted”

2.Deletion_Front()

1. start
2. if rear = = -1
3. print “queue is empty”
4. else
5. if(front = = rear)
a. rear=-1;
b. front=0;
6. else
7. front++;
8. print “ deleted”

3.Insertion_Rear()

1. start
2. if(r==n-1)
3. print “Queue Is Full”
4. else
a. r++;
b. dq[r]=x;
5. print “inserted”

4.Deletion_Rear ()

1. start
2. if rear == -1
3. print “Queue is empty”
4. else
5. if front == rear
a. front =0

Turbomachinery Institute of Technology & Sciences 17 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

b. rear=-1
6. print “deleted”

PROGRAM:

// Program De queue
#include<iostream.h>
#include<conio.h>
#define n 3
template<class t>
class dqueue
{
private:
t dq[n],x;
int i,j,f,r;
public:
dqueue()
{
f=0;
r=-1;
}
void insert_rear();
void insert_front();
void del_rear();
void del_front();
void show();
};
template<class t>
void dqueue<t>::insert_rear()
{
if(r==n-1)
cout<<"\t\t\tQUEUE IS FULL";
else
{
char ch='y';
while(ch=='y')
{
cout<<"ENTER THE DATA:";
cin>>x;
r++;
dq[r]=x;
cout<<"\t\tANY MORE DATA(y/n):";
cin>>ch;
}
}
}

template<class t>
void dqueue<t>::insert_front()
{
if((r==-1) && (f==0))
{
dq[f]=x;

Turbomachinery Institute of Technology & Sciences 18 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

r++;
}
else
{
if((f==0) && (r!=-1))
cout<<"\t\tNOT POSSIBLE TO INSERT";
else
{
char ch='y';
while(ch=='y')
{
if(f==0)
cout<<"\t\tNOT POSSIBLE TO INSERT";
else
{
cout<<"\t\tENTER THE DATA:";
cin>>x;
f--;
dq[f]=x;
cout<<"\t\tANY MORE DATA(y/n):";
cin>>ch;
}
}
}
}
}
template<class t>
void dqueue<t>::del_rear()
{
if(r==-1)
cout<<"\t\t\tQUEUE IS EMPTY";
else
{
if(f==r)
{
f=0;
r=-1;
show();
}
else
{
r--;
show();
}
}
}
template<class t>
void dqueue<t>::del_front()
{
if(r==-1)
cout<<"\t\t\tQUEUE IS EMPTY";
else
{
if(f==r)
{

Turbomachinery Institute of Technology & Sciences 19 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

r=-1;
f=0;
show();
}
else
{
f++;
show();
}
}
}
template<class t>
void dqueue<t>::show()
{
if(r==-1)
cout<<"\t\t\tQUEUE IS EMPTY";
else
{
cout<<"\n\t\tTHE ELEMENTS ARE:"<<"\n\n\t\t\t";
for(i=f;i<=r;i++)
cout<<dq[i]<<"\t";
}
}
template<class t>
void dq_op(dqueue<t> dq)
{
int choice;
do
{
cout<<"\n1.INSERT_REAR"<<"\n";
cout<<"2.INSERT_FRONT"<<"\n";
cout<<"3.DELETE_REAR"<<"\n";
cout<<"4.DELETE_FRONT"<<"\n";
cout<<"5.SHOW"<<"\n";
cout<<"6.EXIT"<<"\n";
cout<<"ENTER THE CHOICE:";
cin>>choice;
switch(choice)
{
case 1:dq.insert_rear();break;
case 2:dq.insert_front();break;
case 3:dq.del_rear();break;
case 4:dq.del_front();break;
case 5:dq.show();break;
case 6:break;
}
}while(choice!=6);
}

main()
{
clrscr();

Turbomachinery Institute of Technology & Sciences 20 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

int ch;
do
{
cout<<"\n1.INT"<<"\n";
cout<<"2.CHAR"<<"\n";
cout<<"3.EXIT"<<"\n";
cout<<"ENTER THE CHOICE:";
cin>>ch;
switch(ch)
{
case 1: dqueue<int> i;
int x1;
dq_op(i);
break;
case 2: dqueue<char> c;
char x2;
dq_op(c);
break;
case 3:break;
}
}while(ch!=3);
}

OUTPUT:
1.INT
2.CHAR
3.EXIT
ENTER THE CHOICE:1
1.INSERT_REAR
2.INSERT_FRONT
3.DELETE_REAR
4.DELETE_FRONT
5.SHOW
6.EXIT
ENTER THE CHOICE:1
ENTER THE DATA:12
ANY MORE DATA(y/n):y
ENTER THE DATA:13
ANY MORE DATA(y/n):n
1.INSERT_REAR
2.INSERT_FRONT
3.DELETE_REAR
4.DELETE_FRONT
5.SHOW
6.EXIT
ENTER THE CHOICE:5
THE ELEMENTS ARE:
12 13
1.INSERT_REAR
2.INSERT_FRONT
3.DELETE_REAR
4.DELETE_FRONT
5.SHOW
6.EXIT
ENTER THE CHOICE:3

Turbomachinery Institute of Technology & Sciences 21 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

THE ELEMENTS ARE:


12

1.INSERT_REAR
2.INSERT_FRONT
3.DELETE_REAR
4.DELETE_FRONT
5.SHOW
6.EXIT
ENTER THE CHOICE:

Turbomachinery Institute of Technology & Sciences 22 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

b) Write a C++ program to implement the deque ( doubly ended


queue ) ADT using a doubly linked list

AIM:
To write a C++ program to implement the deque ADT using a doubly
linked list.

ALGORITHM:

I. Insertion ( ):

1. start
2. * link is a new node
3. read num
4. * n is a new node
5. n → data = num
6. n → link = NULL
7. if front == NULL then
7.1 front = rear = n
7.2 print “no is inserted
7.3 return
8. rear → link = n
9. rear = n
10. print “no is inserted”

II. Deletion ( ):

1. start
2. * d is a new node
3. if front is equal to NULL then
3.1 print “underflow”
3.2 return
4. front is equal to rear then
4.1 front = rear = NULL
4.2 print “no is deleted
4.3 return
5. d = front
6. front = front → link
7. print d → data
8. print “ is deleted”
9. delete d
10. stop

PROGRAM:

#include <iostream.h>
#include <conio.h>
template <class T>
class node
{ node<T> *prev;

Turbomachinery Institute of Technology & Sciences 23 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

T data;
node<T> *next;
public:
friend class Doub<T>;
};
template<class T>
class Doub
{
node<T> *fr;
public:
Doub(){fr = 0;}
~Doub();
void create();
void insert(int , T);
void Delete(int, T &);
void disp();
};
template<class T> Doub<T>::~Doub()
{
node<T> *p=fr;
node<T> *q;
while(p)
{
q=p;
p=p->next;
delete q;
cout<<"object destsroyed"<<endl;
} }
template<class T> void Doub<T>:: create()
{
T data;
char ch;
do
{cout<<"Enter the data element";
cin>>data;
if (fr==0)
{
fr=new node<T>;
fr->prev=0;
fr->data=data;
fr->next=0;
}
else
{
node<T> *q=fr,*r;
while(q->next!=0)
{
q=q-> next;
}
r=new node<T>;
r->data=data;
r->next=0;
r->prev=q;
q->next=r;
}

Turbomachinery Institute of Technology & Sciences 24 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

cout<<"Do you want to continue(Y/N)";


cin>>ch;
}while(ch=='Y'||ch=='y');
}
template<class T> void Doub<T>::insert(int pos,T data)
{
node<T> *q,*temp;
if(pos==0)
{
temp=new node<T>;
temp->prev=0;
temp->data=data;
temp->next=fr;
fr=temp;
}
else
{
node<T> *p=fr;
for(int i=0;i<pos&&p;i++)
p=p->next;
if(p)
{
temp=new node<T>;
temp->data=data;
p->prev->next=temp;
temp->next=p;
p->prev=temp;
}
else
cout<<"Invalid position entered";
}
}
template<class T> void Doub<T>::Delete(int pos,T &data)
{
node<T> *p=fr;
if (pos==0)
{
fr=fr->next;
fr->prev=0;
data=p->data;
delete p;
}
else
{
for(int k=0; k<pos&&p;k++)
p=p->next;
data=p->data;
if(p->next==NULL)
p->prev->next=NULL;
else
{
p->next->prev=p->prev;
p->prev->next=p->next;
}
delete p;

Turbomachinery Institute of Technology & Sciences 25 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

}
}
template <class T> void Doub<T>:: disp()
{
node<T> *curr=fr;
cout<<endl;
while (curr)
{
cout<<curr->data<<"->";
curr=curr->next;
}}
void main()
{
Doub<int> obj;
int pos,data;
clrscr();
cout<<"create method is invocked"<<endl;
obj.create();
cout <<"Display"<<endl;
obj.disp();

cout<<"Enter the position & data";


cin>>pos>>data;
obj.insert(pos,data);
cout<<"Display"<<endl;
obj.disp();
cout<<"enter element position to be deleted \n";
cin>>pos>>data;
obj.Delete(pos,data);
cout<<"Display after Delete";
obj.disp();
getch();
}

OUTPUT:

create method is invoked

Enter the data element2


Do you want to continue(Y/N)y
Enter the data element3
Do you want to continue(Y/N)y
Enter the data element4
Do you want to continue(Y/N)y
Enter the data element5
Do you want to continue(Y/N)n
Display
2->3->4->5->Enter the position & data3
67
Display
2->3->4->67->5->enter element position to be deleted
5
5
Display after Delete
2->3->4->67->5->object destroyed

Turbomachinery Institute of Technology & Sciences 26 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 4. Write a C++ program to perform the following operations.

a. Insert an element into binary search tree


b. Delete an element from binary search tree
c. Search fr a key element in binary search tree.

AIM: To write a c++ program to implement a Binary search tree.

ALGORITHM:

inorder ( node * r) :
1. start
2. if ptr ! = NULL then
3. in order (ptr → LC)
4. print data (ptr)
5. in order (ptr → RC)
6. stop

PROGRAM:

#include <iostream.h>
#include <conio.h>
#define TRUE 1
#define FALSE 0
class btree
{
struct btnode
{
btnode *left;
int data;
btnode *right;
}*root;
public:
btree();
void create(int num);
static void insert(btnode **sr,int);
static void search(btnode **sr,int num,btnode **par,btnode **x,int *found);
void remove(int num);
static void rem(btnode **sr,int num);
void disp();
static void inorder(btnode *sr);
~btree();
static void del(btnode *sr);
};
btree::btree()
{ root=NULL; }
void btree::create(int num)
{
insert(&root,num);
}
void btree::insert(btnode **sr,int num)
{
if(*sr==NULL)

Turbomachinery Institute of Technology & Sciences 27 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

{ *sr=new btnode;
(*sr)->left=NULL;
(*sr)->data=num;
(*sr)->right=NULL;
}
else
{
if(num<(*sr)->data)
insert(&((*sr)->left),num);
else
insert(&((*sr)->right),num);
}}
void btree::remove(int num)
{
rem(&root,num);
}
void btree::rem(btnode **sr,int num)
{
int found;
btnode *parent,*x,*xsucc;
if(*sr==NULL)
{
cout<<"\n Tree is empty";
return;
}
parent=x=NULL;
search(sr,num,&parent,&x,&found);
if(found==FALSE)
{
cout<<"\n data to be deleted, not found";
return;
}
if(x->left!=NULL&&x->right!=NULL)
{
parent=x;
xsucc=x->right;
while(xsucc->left!=NULL)
{
parent=xsucc;
xsucc=xsucc->left;
}
x->data=xsucc->data;
x=xsucc;
}
if(x->left==NULL&&x->right==NULL)
{ if(parent->right==x)
parent->right=NULL;
else
parent->left=NULL;
delete x;
return;
}
if(x->left==NULL&&x->right!=NULL)
{
if(parent->left==x)

Turbomachinery Institute of Technology & Sciences 28 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

parent->left=x->right;
else
parent->right=x->right;
delete x;
return;
}
if(x->left!=NULL&&x->right==NULL)
{
if(parent->left==x)
parent->left=x->left;
else
parent->right=x->left;
delete x;
return;
}}
void btree::search(btnode **sr,int num,btnode **par,btnode **x,int *found)
{
btnode *q;
q=*sr;
*found=FALSE;
*par=NULL;
while(q!=NULL)
{
if(q->data==num)
{
*found=TRUE;
*x=q;
return;
}
*par=q;
if(q->data>num)
q=q->left;
else
q=q->right;
}}
void btree::disp()
{
inorder(root);
}
void btree::inorder(btnode *sr)
{
if(sr!=NULL)
{
inorder(sr->left);
cout<<sr->data<<"\t";
inorder(sr->right);
}}
btree::~btree()
{ del(root);
}
void btree::del(btnode *sr)
{
if(sr!=NULL)
{ del(sr->left);
del(sr->right);

Turbomachinery Institute of Technology & Sciences 29 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

}
delete sr;
}

void main()
{
btree bt;
char ch='y';
int req,i=0,size,num,a[10],elm;
clrscr();
cout<<"Enter size of the tree\n";
cin>>size;
cout<<"enter elements\n";
while(i<=size)
{ cin>>a[i];
bt.create(a[i]);
i++;
}
cout<<"\nBtree before deletion \n";
bt.disp();
while(ch=='y')
{
cout<<"enter deleting elem\n";
cin>>elm;
bt.remove(elm);
cout<<"\nBinary tree after delete\n";
bt.disp();
cout<<"do you want delete ?\n";
cin>>ch;
}
getch();
}

OUTPUT:

Output

Enter size of the tree


3
enter elements
34
23
12
56
Btree before deletion
12 23 34 56
enter deleting elem
34
Binary tree after delete
12 23 56
do you want continue ?
n

Turbomachinery Institute of Technology & Sciences 30 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week 5. Write a C++ program to perform Tree Traversal using Recursive


Functions
a)inorder,
b)preorder
c)postorder

AIM: To write a c++ program to implement a Binary search tree.

ALGORITHM:

I. build ( ):

1. start
2. read num
3. if num is equal to zero then
3.1 root = NULL
4. root = new node
5. root → data = num
6. root → lptr = root → rptr = NULL
7. read num
8. while num ! = 0 then
8.1 n = new node
8.2 n → data = num
8.3 n → lptr = n → rptr = NULL
8.4 s = root
8.5 while s! = NULL
8.6 c = s
8.6.1 if num > s → data
8.6.2 s = s → rptr
8.6.3 else
8.6.4 s = s → lptr
8.6.5 if num > c → data
8.6.6 c →rptr = n
8.6.7 else
8.6.8 c → lptr = n
8.6.9 read num
9. stop

II.Inorder ( node * r) :

1. start
2. if ptr ! = NULL then
3. in order (ptr → LC)
4. print data (ptr)
5. in order (ptr → RC)
6. stop

III.Preorder ( node * r) :

1. start
2. if ptr ! = NULL then

Turbomachinery Institute of Technology & Sciences 31 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

3. print data (ptr)


5. pre order (ptr → LC)
4. pre order (ptr → RC)
5. stop

IV.Postorder ( node * r) :

1. start
2. if ptr ! = NULL then
3. post order (ptr → LC)
4. post order (ptr → RC)
5. print data (ptr)
6. stop

PROGRAM:

#include<iostream.h>
#include<conio.h>
int a[6],i=0;
class list
{
public:
int item;
list *left;
list *right;
};

/* void display(list *t,int i)


{
int j;
if(t!=NULL)
{
display(t->left,i+1);
cout<<" "<<t->item<<endl;
display(t->right,i+1);
}
}
*/
void preorder(list *t)
{
if(t!=NULL)
{
cout<<" "<<t->item;
preorder(t->left);
preorder(t->right);
}
}

Turbomachinery Institute of Technology & Sciences 32 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

void inorder(list *t)


{
if(t!=NULL)
{
inorder(t->left);
cout<<" "<<t->item;
inorder(t->right);
}
}

void postorder(list *t)


{
if(t!=NULL)
{
//cout<<" "<<t->item;
postorder(t->left);
postorder(t->right);
cout<<" "<<t->item;
}
}

list *create(list *t,int item)


{
if(t==NULL)
{
t=new list;
t->left=t->right=NULL;
t->item=item;
a[i]=item;
i++;
return t;
}
else
if(t->item>item)
t->left=create(t->left,item);
else
if(t->item<item)
t->right=create(t->right,item);
else
cout<<endl<<"duplicate elements";
return t;
}
void dis()
{
for(int j=0;j<i;j++)
cout<<a[j]<<endl;
}
void main()
{
list *start=NULL;
int item;
char wish;
clrscr();
do
{

Turbomachinery Institute of Technology & Sciences 33 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

cout<<"enter element";
cin>>item;
start=create(start,item);
cout<<"wish to continue(y/n):";
cin>>wish;
}
while(wish=='Y'||wish=='y');
cout<<endl<<"given btree is:"<<endl;
dis();
cout<<endl<<"preorder";
preorder(start);
cout<<endl<<"Inorder";
inorder(start);
cout<<endl<<"PostOrder";
postorder(start);
getch();
}
Output:
Enter element:9
wish u continue(y/n):y
Enter element:6
wish u continue(y/n):y
Enter element:5
wish u continue(y/n):y
Enter element:4
wish u continue(y/n):y
Enter element:3
wish u continue(y/n):y
Enter element:2
wish u continue(y/n):y
Enter element:1
wish u continue(y/n):n
given btree is:
1
2
3
4
5
6
7
PreOrder:9 6 5 4 3 2 1
InOrder:1 2 3 4 5 6 9
PostOrder:1 2 3 4 5 6 9
Enter element:9
wish u continue(y/n):y
Enter element:7
wish u continue(y/n):y
Enter element:3
wish u continue(y/n):y
Enter element:6
wish u continue(y/n):y
Enter element:2
wish u continue(y/n):y
Enter element:1
wish u continue(y/n):y

Turbomachinery Institute of Technology & Sciences 34 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Enter element:0
wish u continue(y/n):n
Enter element:4
wish u continue(y/n):n

given btree is:


0
1
2
3 4
6
7
PreOrder:7 3 2 1 0 6 4
InOrder:0 1 2 3 4 6 7
PostOrder:0 1 2 4 6 3 7

Turbomachinery Institute of Technology & Sciences 35 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 6. Write a C++ program that uses non-recursive functions to


traverse the given binary tree
a. Preorder
b. Postorder
c. Inorder

AIM:
A c++ program to create a binary tree and traverse it inorder,
preorder, and postorder.

ALGORITHM:

I. build ( ):

1. start
2. read num
3. if num is equal to zero then
3.1 root = NULL
4. root = new node
5. root → data = num
6. root → lptr = root → rptr = NULL
7. read num
8. while num ! = 0 then
8.1 n = new node
8.2 n → data = num
8.3 n → lptr = n → rptr = NULL
8.4 s = root
8.5 while s! = NULL
8.6 c = s
8.6.1 if num > s → data
8.6.2 s = s → rptr
8.6.3 else
8.6.4 s = s → lptr
8.6.5 if num > c → data
8.6.6 c →rptr = n
8.6.7 else
8.6.8 c → lptr = n
8.6.9 read num
9. stop

II.Inorder ( node * r) :

1. start
2. if ptr ! = NULL then
3. in order (ptr → LC)
4. print data (ptr)
5. in order (ptr → RC)
6. stop

III.Preorder ( node * r) :

1. start

Turbomachinery Institute of Technology & Sciences 36 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

2. if ptr ! = NULL then


3. print data (ptr)
5. pre order (ptr → LC)
4. pre order (ptr → RC)
5. stop

IV.Postorder ( node * r) :

1. start
2. if ptr ! = NULL then
3. post order (ptr → LC)
4. post order (ptr → RC)
5. print data (ptr)
6. stop

PROGRAM

#include <iostream.h>
#include <conio.h>
class btre
{
struct bnode
{ bnode *lc;
int data;
bnode *rc;
}*root;
public:
btre();
void ctree(int num);
static void insert(bnode **sr,int num);
void traverse();
static void inorder(bnode *sr);
static void preorder(bnode *sr);
static void postorder(bnode *sr);
static void del(bnode *sr);
~btre();
};
btre::btre()
{ root=NULL;
}
void btre::ctree(int num)
{
insert(&root,num);
}
void btre::insert(bnode **sr,int num)
{
if(*sr==NULL)
{ *sr=new bnode;
(*sr)->lc=NULL;
(*sr)->data=num;
(*sr)->rc=NULL;
return;
}

Turbomachinery Institute of Technology & Sciences 37 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

else
{
if(num<(*sr)->data)
insert(&((*sr)->lc),num);
else
insert(&((*sr)->rc),num);
}
return;
}
void btre::traverse()
{ cout<<"Inordertra\n";
inorder(root);
cout<<"\npre order\n";
preorder(root);
cout<<"\npost order \n";
postorder(root);
}

void btre::inorder(bnode *sr)


{
if(sr!=NULL)
{ inorder(sr->lc);
cout<<"\t"<<sr->data;
inorder(sr->rc);
}
else
return;
}
void btre::preorder(bnode *sr)
{
if(sr!=NULL)
{
cout<<"\t"<<sr->data;
preorder(sr->lc);
preorder(sr->rc);
}
else
return;
}
void btre::postorder(bnode *sr)
{
if(sr!=NULL)
{
postorder(sr->lc);postorder(sr->rc);
cout<<"\t"<<sr->data;
}
else
return;
}
btre::~btre()
{
del(root);
}
void btre::del(bnode *sr)
{

Turbomachinery Institute of Technology & Sciences 38 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

if(sr!=NULL)
{ del(sr->lc);
del(sr->rc);
}
delete sr;
}

void main()
{
btre bt;
int req,i=1,num;

clrscr();
cout<<"specify the no of items to be inserted \n";
cin>>req;
while(i++<=req)
{
cout<<"enter the data \n";
cin>>num;
bt.ctree(num);
}
bt.traverse();
getch();
}

OUTPUT:

specify the no of items to be inserted


5
enter the data
12
enter the data
23
enter the data
34
enter the data
11
enter the data
45
Inorder
11 12 23 34 45

pre order
12 11 23 34 45
post order
11 45 34 23 12

Turbomachinery Institute of Technology & Sciences 39 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week 7.a)Write a C++ program for the implementation of DFS for Graph

AIM: A c++ program to implement the depth first search algorithm for the
given graph.

ALGORITHM:

I. DFS (int i)
1. start
2. visited [i] = 1
3. print “Node visited”
4. print i = i + 1
5. for j = 0 to max size
5.1 if ((visisted [j] ==0) && graph [i][j] ==1))
5.2 dfs(j);
6. stop

PROGRAM:

#include <iostream.h>
#include <conio.h>
#define TRUE 1
#define FALSE 0
const int MAX=8;
struct node
{
int data;
node *next;
};
class graph
{
int visit[MAX];
public:
graph();
void dfs(int v,node **p);
node *getn(int val);
void del(node *n);
};
graph::graph()
{
for(int i=0;i<MAX;i++)
visit[i]=FALSE;
}
void graph::dfs(int v,node **p)
{
node *t;
visit[v-1]=TRUE;
cout<<v<<"\t";
t=*(p+v-1);
while(t!=NULL)
{
if( visit[t->data-1]==FALSE)
dfs(t->data,p);

Turbomachinery Institute of Technology & Sciences 40 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

else
t=t->next;
} }
node *graph::getn(int val)
{
node *newnode=new node;
newnode->data=val;
return newnode;
}
void graph::del(node *n)
{
node *temp;
while(n!=NULL)
{
temp=n->next;
delete n;
n=temp;
} }
void main()
{
node *arr[MAX];
node *v1,*v2,*v3,*v4;
graph g;
clrscr();
v1=g.getn(2);
arr[0]=v1;
v1->next=v2=g.getn(3);
v2->next=NULL;
v1=g.getn(1);
arr[1]=v1;
v1->next=v2=g.getn(4);
v2->next=v3=g.getn(5);
v3->next=NULL;
v1=g.getn(1);
arr[2]=v1;
v1->next=v2=g.getn(6);
v2->next=v3=g.getn(7);
v3->next=NULL;
v1=g.getn(2);
arr[3]=v1;
v1->next=v2=g.getn(8);
v2->next=NULL;
v1=g.getn(2);
arr[4]=v1;
v1->next=v2=g.getn(8);
v2->next=NULL;
v1=g.getn(3);
arr[5]=v1;
v1->next=v2=g.getn(8);
v2->next=NULL;
v1=g.getn(3);
arr[6]=v1;
v1->next=v2=g.getn(8);
v2->next=NULL;
v1=g.getn(4);

Turbomachinery Institute of Technology & Sciences 41 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

arr[7]=v1;
v1->next=v2=g.getn(5);
v2->next=v3=g.getn(6);
v3->next=v4=g.getn(7);
v4->next=NULL;
cout<<endl;
cout<<"dfs format is \n:";
g.dfs(1,arr);
cout<<"\n array after deletion \n";
for(int i=0;i<MAX;i++)
g.del(arr[i]);}

OUTPUT:

dfs format is
:1 2 4 8 5 6 3 7

Graph after deletion

Turbomachinery Institute of Technology & Sciences 42 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

b) Write a C++ program for the implementation of BFS for Graph.

AIM:
A c++ program to implement the breadth first search algorithm for
the given graph.

ALGORITHM:
1. bfs (int) :
1. start
2. visited [i] = 1
3. addq [i]
4. while front ! = rear
4.1 i = deleteq ( )
4.2 i = i + 1
5. for j = 0 to max size
6. if visited [j] ==0 && graph [i][j] == 1 then
6.1 addq (i)
6.2 visited [j] = 1
7. j = j+1
8. stop

PROGRAM:

#include<iostream.h>
#include <conio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
const int MAX=8;
struct node
{
int data;
node*next;
};
class graph
{
private:
int visited[MAX];
int q[8];
int front, rear;
public:
graph();
void bfs(int v, node **p);
node *getnode_write(int val);
static void addqueue(int *a, int vertex,int *f, int *r);
static int deletequeue(int *q,int *f,int *r);
static int isempty(int *f);
void del(node *n);
};
graph::graph()
{

Turbomachinery Institute of Technology & Sciences 43 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

for(int i=0;i<MAX;i++)
visited[i]=FALSE;
front=rear=-1;
}
void graph::bfs(int v, node **p)
{
node *u;
visited[v-1]=TRUE;
cout<<v<<"\t";
addqueue(q,v,&front,&rear);
while(isempty(&front)==FALSE)
{
v=deletequeue(q,&front,&rear);
u=*(p+v-1);
while(u!=NULL)
{
if(visited[u->data-1]==FALSE)
{
addqueue(q,u->data,&front,&rear);
visited[u->data-1]=TRUE;
cout<<u->data<<"\t";
}
u=u->next;
}
}
}
node *graph::getnode_write(int val)
{
node *newnode=new node;
newnode->data=val;
return newnode;
}
void graph::addqueue(int *a,int vertex, int *f, int *r)
{
if(*r==MAX-1)
{
cout<<"\n Queue Overflow.";
exit(0);
}
(*r)++;
a[*r]=vertex;
if(*f==-1)
*f=0;
}
int graph::deletequeue(int *a,int *f, int *r)
{
int data;
if(*f==-1)
{
cout<<"\nQueue Underflow.";
exit(0);
}
data=a[*f];
if(*f==*r)
*f=*r=-1;

Turbomachinery Institute of Technology & Sciences 44 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

else
(*f)++;
return data;
}
int graph::isempty(int *f)
{
if(*f==-1)
return TRUE;
return FALSE;
}
void graph::del(node *n)
{
node *temp;
while(n!=NULL)
{
temp=n->next;
delete n;
n=temp;
}
}
void main()
{
node *arr[MAX];
node *v1,*v2,*v3,*v4;
graph g;
clrscr();
cout<<"Graph before deletion\n";
v1=g.getnode_write(2);
arr[0]=v1;
v1->next=v2=g.getnode_write(3);
v2->next=NULL;
v1=g.getnode_write(1);
arr[1]=v1;
v1->next=v2=g.getnode_write(4);
v2->next=v3=g.getnode_write(5);
v3->next=NULL;
v1=g.getnode_write(1);
arr[2]=v1;
v1->next=v2=g.getnode_write(6);
v2->next=v3=g.getnode_write(7);
v3->next=NULL;
v1=g.getnode_write(2);
arr[3]=v1;
v1->next=v2=g.getnode_write(8);
arr[4]=v1;
v1->next=v2=g.getnode_write(8);
v2->next=NULL;
v1=g.getnode_write(3);
arr[5]=v1;
v1->next=v2=g.getnode_write(8);
v2->next=NULL;
v1=g.getnode_write(3);
arr[6]=v1;
v1->next=v2=g.getnode_write(8);
v2->next=NULL;

Turbomachinery Institute of Technology & Sciences 45 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

v1=g.getnode_write(4);
arr[7]=v1;
v1->next=v2=g.getnode_write(5);
v2->next=v3=g.getnode_write(6);
v3->next=v4=g.getnode_write(7);
v4->next=NULL;
cout<<endl;
g.bfs(1,arr);
cout<<"\nGraph after deletion\n";
for(int i=0;i<MAX;i++)
g.del(arr[i]);
getch();
}
OUTPUT:

Graph before deletion:1 2 3 4 5 6 7 8

Turbomachinery Institute of Technology & Sciences 46 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week 8.a) Write a C++ program to implement the Merge sort

AIM:
To implement a c++ program for one of the sorting technique.

ALGORITHM:

I. Merge (k, first, second, third):


1. Initialization of the variables
f = first
s = second
i=0
2. Repeat while (f<second and s <= third)
if (k[f] = k[s]) then
{
i =i+1
temp [i] = k[f]
f=f+1
}
else
{
i=i+1
temp [i] = k[s]
s=s+1
}
3. store the elements which are not processed
if (f>= second) then repeat while (s<=third)
{
i = i +1
temp [i] = k[s]
s=s+1
}
else
repeat while (f< second)
{
i=i +1
temp[i] = k[f]
f=f+1
}
4. get back the elements from the temporary elements
repeat for i = 1 to n do
k [first – 1 + i] = temp [i]
5. return

Turbomachinery Institute of Technology & Sciences 47 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

PROGRAM:

#include <iostream.h>
#include <conio.h>
class merges
{
public:
void msort(int,int *,int,int *,int *);
void bsort(int,int *);
};
void merges::bsort(int n,int a[])
{
int flag=1;
for(int j=0;j<n-1;j++)
{
for(int k=0;k<n-j-1;k++)
{
if(a[k]>a[k+1])
{
int temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
flag=0;
}}
if(flag)
break;
else
flag=1;
}
cout<<"\nentered list is \n";
cout<<"\nascending order\n";
for(int i=0;i<n;i++)
cout<<" "<<a[i];
}
void merges::msort(int n,int a[],int m,int b[],int c[])
{
int i=0,j=0,k=0;
cout<<"\nMERGED ARRAY IS \n";
while((i<n) && (j<m))
{
if(a[i]<b[j])
{c[k]=a[i];
i++;
k++;
}
else
if(a[i]>b[j])
{ c[k]=b[j];
j++;
k++;
}
else
{

Turbomachinery Institute of Technology & Sciences 48 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

c[k]=a[i];
i++;j++;k++;
}
cout<<endl;
for(int ch=0;ch<k;ch++)
cout<<" "<<c[ch];
}
if(i<n)
{ for(int l=i;l<n;l++)
{
c[k]=a[i];
j++;k++;} cout<<endl;
for(int ch=0;ch<k;ch++)
cout<<" "<<c[ch];
}
else
if(j<m)
{ for(int l=j;l<m;l++)
{ c[k]=b[j];
j++;k++; }}
cout<<endl;
for(int ch=0;ch<k;ch++)
cout<<" "<<c[ch];

}
void main()
{
merges ms;
int a[20],b[20],c[40];
int n,m,k,i;
clrscr();
cout<<"enter n value\n";
cin>>n;
cout<<"\nenter elements \n";
for(i=0;i<n;i++)
cin>>a[i];
ms.bsort(n,a);
cout<<"\nenter m value\n";
cin>>m;
cout<<"\nenter elements\n";
for(i=0;i<m;i++)
cin>>b[i];
ms.bsort(m,b);
ms.msort(n,a,m,b,c);
getch();
}

Turbomachinery Institute of Technology & Sciences 49 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

OUTPUT:

enter n value
5
enter elements
1
4
23
12
56
entered list is
ascending order
1 4 12 23 56
enter m value
3
enter elements
13
12
1
entered list is
ascending order
1 12 13

MERGED ARRAY IS
1
14
1 4 12
1 4 12 13
1 4 12 13 23 23
1 4 12 13 23 23

Turbomachinery Institute of Technology & Sciences 50 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

b) Write a C++ program to implement the Heap sort

AIM:
A C++ program to implement Heap Sort

ALGORITHM:

I. heapSort(a, count)

1. end := count - 1
2. while end > 0 do
3. swap the root(ma value) of the heap with the last element of the heap)
swap(a[end], a[0])
4. decrease the size of the heap by one so that the previous max value
will stay in its proper placement)
5. end := end - 1
6. (put the heap back in max-heap order)
7. siftDown(a, 0, end)

II.heapify(a,count)

1. (start is assigned the index in a of the last parent node)


2. start := (count - 1) / 2
3. while start ≥ 0 do
4. (sift down the node at index start to the proper place such that all
nodes below the start index are in heap order)
5. siftDown(a, start, count-1)
6. start := start – 1
7. (after sifting down the root all nodes/elements are in heap order)

III.siftDown(a, start, end)

1. root := start
2. while root * 2 + 1 ≤ end do
3. (While the root has at least one child)
4. child := root * 2 + 1 (root*2+1 points to the left child)
5. (If the child has a sibling and the child's value is less than its
sibling's...)
6. if child < end and a[child] < a[child + 1] then
7. child := child + 1 (... then point to the right child instead)
8. if a[root] < a[child] then (out of max-heap order)
9. swap(a[root], a[child])
10. root := child (repeat to continue sifting down the child now)
11. else 12. return

PROGRAM:

#include <iostream.h>
#include <conio.h>
void hsort(int x[],int n)
{

Turbomachinery Institute of Technology & Sciences 51 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

int i,elt,s,f,ivalue;
for(i=1;i<n;i++)
{
elt=x[i];
s=i;
f=(s-1)/2;
while(s>0 && (x[f]<elt))
{
x[s]=x[f];
s=f;
f=(s-1)/2;
}
x[s]=elt;
}
for(i=n-1;i>0;i--)
{ivalue=x[i];
x[i]=x[0];
f=0;
if(i==1)
s=-1;
else
s=1;
if((i>2) && (x[2]>x[1]))
s=2;
while((s>=0) && (ivalue<x[s]))
{
x[f]=x[s];
f=s;
s=2*f+1;
if((s+1<=i-1) && (x[s]<x[s+1]))
s=s+1;
if(s>i-1)
s=-1;
}
x[f]=ivalue;
}}
void main()
{
int i,size,a[10];
clrscr();
cout<<"enter the size\n";
cin>>size;
cout<<"enter elements\n";
for(i=0;i<size;i++)
cin>>a[i];
hsort(a,size);
cout<<"sorted array \n";
for(i=0;i<size;i++)
cout<<a[i]<<endl;
getch();
}

Turbomachinery Institute of Technology & Sciences 52 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

OUTPUT:
enter the size
3
enter elements
12
1
4
sorted array
1 4 12

Turbomachinery Institute of Technology & Sciences 53 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 9. Write a C++ program to perform the following operations


a. Insertion int a B-Tree
b. Deletion from a B-Tree

AIM:
A C++ Program to perform insertion and deletion on B-Tree

ALGORITHM:

I.B-Tree-Insert(T, k)

1. r <- root[T]
2. if n[r] = 2t - 1
a. then s <- Allocate-Node()
b. root[T] <- s
c. leaf[s] <- FALSE
d. n[s] <- 0
e. c1 <- r
f. B-Tree-Split-Child(s, 1, r)
g. B-Tree-Insert-Nonfull(s, k)
h. else B-Tree-Insert-Nonfull(r, k)

II. B-Tree-Delete(x, k)

1. if x is a leaf then
2. if k is in x then
3. delete k from x and return true
4. else return false //k is not in subtree
5. else //x is an internal node
6. if k is in x then
7. y = the child of x that precedes k
a. if y has at least t keys then
b. k' = the predecessor of k (use B-Tree-FindLargest)
c. Copy k' over k //i.e., replace k with k'
B-Tree-Delete(y, k') //Note: recursive call
8. else //y has t-1 keys
9. z = the child of x that follows k
10. if z has at least t keys then
11.k' = the successor of k
12.Copy k' over k //i.e., replace k with k'
13.B-Tree-Delete(z, k') //Note: recursive call
14.stop

PROGRAM:

#include <iostream.h>
#include <conio.h>
class btre
{
struct node
{

Turbomachinery Institute of Technology & Sciences 54 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

node *left;
char data;
node *right;
}*root;
char *a;
int *lc;int *rc;
public:
btre(char *,int *l,int *r,int size);
void insert(int index);
static node *create(char *a1,int *l,int *r,int index);
void display();
static void inorder(node *sr);
~btre();
static void del(node *sr);
};
btre::btre(char *a1,int *l,int *r,int size)
{
root=NULL;
a=new char[size];
lc=new int[size];
rc=new int[size];
for(int i=0;i<size;i++)
{ *(a1+i)=*(a1+i);
*(lc+i)=*(l+i);
*(rc+i)=*(r+i);
}}
void btre::insert(int index)
{
root=create(a,lc,rc,index);
}
node *btre::create(char *a1,int *l,int *r,int index)
{
node *temp=NULL;
if(index!=-1)
{ temp=new node;
temp->left=create(a1,l,r,*(l+index));
temp->data=*(a1+index);
temp->right=create(a1,l,r,*(r+index));
}
return temp;
}
void btre::display()
{
inorder(root);
}
void btre::inorder(node *sr)
{
if(sr!=NULL)
{ inorder(sr->left);
cout<<sr->data<<"\t";
inorder(sr->right);
}}
btre::~btre()
{
delete a;

Turbomachinery Institute of Technology & Sciences 55 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

delete lc;
delete rc;
del(root);
}
void btre::del(node *sr)
{
if(sr!=NULL)
{ del(sr->left);
del(sr->right);
}
delete sr;
}
void main()
{
char a1[15];
int l[15];
int r[15];
int sz;
clrscr();
cout<< "enter the size\n";
cin>>sz;
int sz1=sizeof(sz);
cout<<"enter the elements \n";
for(int i=0;i<sz1;i++)
{cin>>a1[i];}
btre bt(a1,l,r,sz);
bt.insert(0);
cout<<"\n in-order traversal : "<<endl;
bt.display();
getch();
}

OUTPUT:

Enter size of the tree


6
enter elements
12
56
232
45
56
67
78

Btree before deletion


12 45 56 56 67 78 232 enter deleting elem
67

Binary tree after delete


12 45 56 56 78 232 do you want delete ?
n

Turbomachinery Institute of Technology & Sciences 56 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 10. Write a C++ program to perform the following operations


a.Insertion into an AVL Tree b.Deletion from an AVL Tree

AIM:
A C++ program to implement AVL Trees.

ALGORITHM:

I. INSERT:

1 Do Binary Search Tree Insert (recursive algorithm)

2 While the recursion returns, keep track of

a. node p,
b. p's child q and
c. p's grandchild r within the path from inserted node to p.

3 If p is unbalanced, do one of the following rotations:

a. if (p.left == q) and (p.left.left == r), single rotation right in p;


b. if (p.right == q) and (p.right.right == r), single rotation left in p;
c. if (p.left == q) and (p.left.right == r), LR-double rotation in p; or
d. if (p.right == q) and (p.right.left == r), RL-double rotation in p.

II. DELETE:

1. Let ptr, p be a reference to a Node.


2. ptr = find(X
3. If ptr is not null,
4. Decrement elementCount;
5. If ptr == root
6. Set root to null and return
7. If ptr is a leaf node,
8. p = ptr.parent
9. Set p's left/right child to null.
10. Else If ptr is a node with 1 child (left/right),
11. p = ptr.parent;
12. Set p's left/right child to be ptr's left/right child.
13. Else
14. Let ptr2 be a Node*.
15. ptr2 = findMin(ptr.right);
16. ptr.element = ptr2.element;
17. p = ptr2.parent
18. Set p's left child to be ptr2's right child.

PROGRAM:

#include <iostream.h>
#include <stdlib.h>

#define FALSE 0
#define TRUE 1

Turbomachinery Institute of Technology & Sciences 57 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

struct AVLNode
{
int data ;
int balfact ;
AVLNode *left ;
AVLNode *right ;
};

class avltree
{
private :

AVLNode *root ;

public :

avltree( ) ;
AVLNode* insert ( int data, int *h ) ;
static AVLNode* buildtree ( AVLNode *root, int data, int *h ) ;
void display( AVLNode *root ) ;
AVLNode* deldata ( AVLNode* root, int data, int *h ) ;
static AVLNode* del ( AVLNode *node, AVLNode* root, int *h ) ;
static AVLNode* balright ( AVLNode *root, int *h ) ;
static AVLNode* balleft ( AVLNode* root, int *h ) ;
void setroot ( AVLNode *avl ) ;
~avltree( ) ;
static void deltree ( AVLNode *root ) ;
};

// initialises data member


avltree :: avltree( )
{
root = NULL ;
}

// inserts an element in a binary tree by calling buildtree


AVLNode* avltree :: insert ( int data, int *h )
{
root = buildtree ( root, data, h ) ;
return root ;
}

// inserts an element into tree


AVLNode* avltree :: buildtree ( AVLNode *root, int data, int *h )
{
AVLNode *node1, *node2 ;

if ( root == NULL )
{
root = new AVLNode ;
root -> data = data ;
root -> left = NULL ;
root -> right = NULL ;

Turbomachinery Institute of Technology & Sciences 58 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

root -> balfact = 0 ;


*h = TRUE ;
return ( root ) ;
}

if ( data < root -> data )


{
root -> left = buildtree ( root -> left, data, h ) ;

// If left subtree is higher


if ( *h )
{
switch ( root -> balfact )
{

case 1 :

node1 = root -> left ;


if ( node1 -> balfact == 1 )
{
cout << "\nRight rotation." ;
root -> left = node1 -> right ;
node1 -> right = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
cout << "\nDouble rotation, left then right." ;
node2 = node1 -> right ;
node1 -> right = node2 -> left ;
node2 -> left = node1 ;
root -> left = node2 -> right ;
node2 -> right = root ;

if ( node2 -> balfact == 1 )


root -> balfact = -1 ;
else
root -> balfact = 0 ;
if ( node2 -> balfact == -1 )
node1 -> balfact = 1 ;
else
node1 -> balfact = 0 ;
root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
break ;

case 0 :

root -> balfact = 1 ;


break ;

case -1 :

Turbomachinery Institute of Technology & Sciences 59 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

root -> balfact = 0 ;


*h = FALSE ;
}
}
}

if ( data > root -> data )


{
root -> right = buildtree ( root -> right, data, h ) ;

// If the right subtree is higher


if ( *h )
{
switch ( root -> balfact )
{

case 1 :

root -> balfact = 0 ;


*h = FALSE ;
break ;

case 0 :

root -> balfact = -1 ;


break ;

case -1 :

node1 = root -> right ;


if ( node1 -> balfact == -1 )
{
cout << "\nLeft rotation." ;
root -> right = node1 -> left ;
node1 -> left = root ;
root -> balfact = 0 ;
root = node1 ;
}
else
{
cout << "\nDouble rotation, right then left." ;
node2 = node1 -> left ;
node1 -> left = node2 -> right ;
node2 -> right = node1 ;
root -> right = node2 -> left ;
node2 -> left = root ;

if ( node2 -> balfact == -1 )


root -> balfact = 1 ;
else
root -> balfact = 0 ;
if ( node2 -> balfact == 1 )
node1 -> balfact = -1 ;
else

Turbomachinery Institute of Technology & Sciences 60 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

node1 -> balfact = 0 ;


root = node2 ;
}
root -> balfact = 0 ;
*h = FALSE ;
}
}
}
return ( root ) ;
}

// prints data
void avltree :: display ( AVLNode* root )
{
if ( root != NULL )
{
display ( root -> left ) ;
cout << root -> data << "\t" ;
display ( root -> right ) ;
}
}

// To delete an item from the tree


AVLNode* avltree :: deldata ( AVLNode *root, int data, int *h )
{
AVLNode *node ;

if ( root -> data == 13 )


cout << root -> data ;

if ( root == NULL )
{
cout << "\nNo such data." ;
return ( root ) ;
}
else
{
if ( data < root -> data )
{
root -> left = deldata ( root -> left, data, h ) ;
if ( *h )
root = balright ( root, h ) ;
}
else
{
if ( data > root -> data )
{
root -> right = deldata ( root -> right, data, h ) ;
if ( *h )
root = balleft ( root, h ) ;
}
else
{
node = root ;
if ( node -> right == NULL )

Turbomachinery Institute of Technology & Sciences 61 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

{
root = node -> left ;
*h = TRUE ;
delete ( node ) ;
}
else
{
if ( node -> left == NULL )
{
root = node -> right ;
*h = TRUE ;
delete ( node ) ;
}
else
{
node -> right = del ( node -> right, node, h ) ;
if ( *h )
root = balleft ( root, h ) ;
}
}
}
}
}
return ( root ) ;
}

AVLNode* avltree :: del ( AVLNode *succ, AVLNode *node, int *h )


{
AVLNode *temp = succ ;

if ( succ -> left != NULL )


{
succ -> left = del ( succ -> left, node, h ) ;
if ( *h )
succ = balright ( succ, h ) ;
}
else
{
temp = succ ;
node -> data = succ -> data ;
succ = succ -> right ;
delete ( temp ) ;
*h = TRUE ;
}
return ( succ ) ;
}

// To balance the tree, if right sub-tree is higher


AVLNode* avltree :: balright ( AVLNode *root, int *h )
{
AVLNode *temp1, *temp2 ;

switch ( root -> balfact )


{

Turbomachinery Institute of Technology & Sciences 62 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

case 1 :

root -> balfact = 0 ;


break ;

case 0 :

root -> balfact = -1 ;


*h = FALSE ;
break ;

case -1 :

temp1 = root -> right ;


if ( temp1 -> balfact <= 0 )
{
cout << "\nLeft rotation." ;
root -> right = temp1 -> left ;
temp1 -> left = root ;

if ( temp1 -> balfact == 0 )


{
root -> balfact = -1 ;
temp1 -> balfact = 1 ;
*h = FALSE ;
}
else
{
root -> balfact = temp1 -> balfact = 0 ;
}
root = temp1 ;
}
else
{
cout << "\nDouble rotation, right then left." ;
temp2 = temp1 -> left ;
temp1 -> left = temp2 -> right ;
temp2 -> right = temp1 ;
root -> right = temp2 -> left ;
temp2 -> left = root ;

if ( temp2 -> balfact == -1 )


root -> balfact = 1 ;
else
root -> balfact = 0 ;
if ( temp2 -> balfact == 1 )
temp1 -> balfact = -1 ;
else
temp1 -> balfact = 0 ;
root = temp2 ;
temp2 -> balfact = 0 ;
}
}
return ( root ) ;
}

Turbomachinery Institute of Technology & Sciences 63 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

// To balance the tree, if left sub-tree is higher


AVLNode* avltree :: balleft ( AVLNode *root, int *h )
{
AVLNode *temp1, *temp2 ;

switch ( root -> balfact )


{

case -1 :

root -> balfact = 0 ;


break ;

case 0 :

root -> balfact = 1 ;


*h = FALSE ;
break ;

case 1 :

temp1 = root -> left ;


if ( temp1 -> balfact >= 0 )
{
cout << "\nRight rotation." ;
root -> left = temp1 -> right ;
temp1 -> right = root ;

if ( temp1 -> balfact == 0 )


{
root -> balfact = 1 ;
temp1 -> balfact = -1 ;
*h = FALSE ;
}
else
{
root -> balfact = temp1 -> balfact = 0 ;
}
root = temp1 ;
}
else
{
cout << "\nDouble rotation, left then right." ;

temp2 = temp1 -> right ;


temp1 -> right = temp2 -> left ;
temp2 -> left = temp1 ;
root -> left = temp2 -> right ;
temp2 -> right = root ;

if ( temp2 -> balfact == 1 )


root -> balfact = -1 ;
else
root -> balfact = 0 ;

Turbomachinery Institute of Technology & Sciences 64 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

if ( temp2-> balfact == -1 )
temp1 -> balfact = 1 ;
else
temp1 -> balfact = 0 ;
root = temp2 ;
temp2 -> balfact = 0 ;
}
}
return ( root ) ;
}

// sets new the root node


void avltree :: setroot ( AVLNode *avl )
{
root = avl ;
}

// calls deltree to deallocate memory


avltree :: ~avltree( )
{
deltree ( root ) ;
}

// deletes the tree


void avltree :: deltree ( AVLNode *root )
{
if ( root != NULL )
{
deltree ( root -> left ) ;
deltree ( root -> right ) ;
}
delete ( root ) ;
}

void main( )
{
avltree at ;
AVLNode *avl = NULL ;
int h ;

avl = at.insert ( 20, &h ) ;


at.setroot ( avl ) ;
avl = at.insert ( 6, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 29, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 5, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 12, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 25, &h ) ;
at.setroot ( avl ) ;

Turbomachinery Institute of Technology & Sciences 65 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

avl = at.insert ( 32, &h ) ;


at.setroot ( avl ) ;
avl = at.insert ( 10, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 15, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 27, &h ) ;
at.setroot ( avl ) ;
avl = at.insert ( 13, &h ) ;
at.setroot ( avl ) ;

cout << endl << "AVL tree:\n" ;


at.display ( avl ) ;

avl = at.deldata ( avl, 20, &h ) ;


at.setroot ( avl ) ;
avl = at.deldata ( avl, 12, &h ) ;
at.setroot ( avl ) ;

cout << endl << "AVL tree after deletion of a node:\n" ;


at.display ( avl ) ;
}

OUTPUT:

Enter your choice


1
enter the size
1
14
MENU
1. Insert
2. Search
3. Delete
4. Display
5. Quit
Enter your choice

5
Sorry

Left rotation.
AVL tree:
5 6 10 12 13 15 20 25 27 29
32
AVL tree after deletion of a node:
5 6 10 13 15 25 27 29 32
Left rotation.
AVL tree:
5 6 10 12 13 15 20 25 27 29

Turbomachinery Institute of Technology & Sciences 66 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 11. Write a C++ program to implement all the functions of a


dictionary (ADT) using hashing.

AIM:
A C++ Program to implement dictionary (ADT) using hashing

PROGRAM:

#include <iostream.h>
#include <conio.h>
#include <process.h>
void init(int h[]);
void insert(int h[],int);
void search(int h[],int);
void Delete(int h[],int);
void disp();
void insert(int h[],int a)
{
int r,i;
r=a%10;
i=r;
if(h[i]==0)
h[i]=a;
else
i--;
h[i]=a;
}
void search(int h[],int key)
{
int i,r;
r=key%10;
while(h[r]!=0)
{
if(h[r]==key)
{cout<<"found";
break;
}
else
r--;
if(h[r]!=key)
cout<<"not found";
} }
void init(int h[])
{
int i;
for(i=0;i<10;i++)
h[i]=0;
}
void Delete(int h[],int e)
{
int i,r;
r=e%10;

Turbomachinery Institute of Technology & Sciences 67 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

while(h[r]!=0)
{
if(h[r]==e)
{cout<<"found";
h[r]=0;break;
}
else
r--;
if(h[r]!=e)
cout<<"not found";
}}
void disp(int h[])
{
int i;
cout<<"Array is \n";
for(i=0;i<10;i++)
{
cout<<h[i];
cout<<endl;}
}
void main()
{
int h[10],size,i,a,ch=0,key;
clrscr();
init(h);
do
{
cout<<" MENU \n";
cout<<"1. Insert\n";
cout<<"2. Search\n";
cout<<"3. Delete\n";
cout<<"4. Display\n";
cout<<"5. Quit\n ";
cout<<"Enter your choice\n";
cin>>ch;
switch(ch)
{
case 1:
{
cout<<"enter the size\n";
cin>>size;
for(i=0;i<size;i++)
{cin>>a;
insert(h,a);
}break;}
case 2:
{
cout<<"Enter the element to be searched\n";
cin>>key;
search(h,key);
break;
}
case 3:
{
cout<<"Enter the element to be deleted\n";

Turbomachinery Institute of Technology & Sciences 68 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

cin>>a;
Delete(h,a);
break;
}
case 4:
{
disp(h);
break;
}
default: cout<<"Sorry\n";
}}while(ch!=5);
getch();
}

OUTPUT:

MENU
1. Insert
2. Search
3. Delete
4. Display
5. Quit
Enter your choice
1
enter the size
2
13
12
MENU
1. Insert
2. Search
3. Delete
4. Display
5. Quit
Enter your choice
4
Array is
0
0
12
13
0
0
0
MENU
Turbomachinery Institute of Technology & Sciences 69 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

1. Insert
2. Search
3. Delete
4. Display
5. Quit
Enter your choice
1
enter the size
1
14
MENU
1. Insert
2. Search
3. Delete
4. Display
5. Quit
Enter your choice

Turbomachinery Institute of Technology & Sciences 70 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

Week: 12 Write a C++ program to implement Knuth – Morris – Pratt


Algorithm.

AIM: A C++ Program to implement Knuth – Morris – Pratt


Algorithm.

ALGORITHM:

KMPMatch(T,P):
Input: String T (text) with n characters and P (pattern) with m characters
Output: Starting index of the first sub string of T matching P, or an indication
that Pis not sub string of T.

f<-KMPFailureFunction(P){
construct the failure function f for P
}
i<- 0
j<- 0
while i<n do
if P[j]=T[i] then
if j=m-1 then
return i-m+1 { a match!}
i<-i+1
j<-J+1
else if j>0 { no match, but we have advanced in P} then
j<--f(j-1){ j indexes just after prefix of P that must match}
else
i<--i+1
return “There is no sub string of T matching P”.

KMPFailreFunction(P):
Input : String P(pattern) with m characters
Output: The failure function f for P, which maps j to the length okf the
longest prefix of P that is a suffix of P[1...j]

i<--1
j<--0
f(0) <--0
whilei<m do
if P[j] = P[i] then
{ we have matched j+1 characters}
f9i0<--j+1
i<-- i+1
j<-- j+1
else if j>0 then { j indexes just after a prefix of P that must match}
j<--f(j-1)
else
{we have no match here}
f(i)<—0
i<-- i+1

Turbomachinery Institute of Technology & Sciences 71 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

PROGRAM:

#include<stdio.h>
#include<iostream.h>
#include<string.h>
#include<conio.h>
static kmp(char *ptr_i,char *ptr_m,int word_length,int sentence_length);
static kmp_table(char *ptr_i,char *ptr_m,int word_length,int sentence_length);
char T[50];

int main()
{
char word[10],sentence[40];
char *ptr_i,*ptr_m;
int word_length,sentence_length;
ptr_i=word;
ptr_m=sentence;
cout<<"Enter the word";
cin>>word;
word_length=strlen(word);
getchar();
cout<<"Enter the sentence\n";
fgets(sentence,40,stdin);
sentence_length=strlen(sentence);
kmp_table(ptr_i,ptr_m,word_length,sentence_length);
kmp(ptr_i,ptr_m,word_length,sentence_length);
getch();
return 0;// return zero
}

kmp(char *ptr_i,char *ptr_m,int word_length,int sentence_length)


{
int pos,m=0,i=0;
<strong class="highlight">for</strong>(;m<sentence_length; )
{
if(*(ptr_i+i) == *(ptr_m+m+i))
{
i=i+1;
if(i==word_length)
{
pos=m+1;
cout<<"The word was found at position %d\n"<<pos;
}
}
else
{
m=m+i-T[i];
if(i>0)
i=T[i];
}
}

Turbomachinery Institute of Technology & Sciences 72 Computers Science & Engg. Dept.
Data Structure Through C++ Lab

return sentence_length;
}

kmp_table(char *ptr_i,char *ptr_m,int word_length,int sentence_length)


{
int i,j;
i=2;
j=0;
T[0]=-1;
T[1]=0;
for(;i<word_length; )
{
if(*(ptr_i+i-1) == *(ptr_i+j))
{
T[i]=j+1;
i=i+1;
j=j+1;
}

else if(j>0)
{
j=T[j];
}

else
{
T[i]=0;
i=i+1;
}
}
}

OUTPUT:

Enter the word:


C++
Enter the sentence
I like c++ lab
The word was found at position : 8

Turbomachinery Institute of Technology & Sciences 73 Computers Science & Engg. Dept.