Você está na página 1de 110

1.

WRITE C++ PROGRAMS TO IMPLEMENT FOLLOWING USING AN ARRAY:


A)STACK ADT B) QUEUE ADT

A) STACK: DESCRIPTION: Stack is a linear data structure, it will be having an end called top, and the possible operations are PUSH(), POP(), TRAVERSE(). PUSH() and POP() will be done at the top. We use stack in applications like conversion of expressions, parenthesis matching etc.. ALGORITHM:

Main Step 1: Start Step 2: Create objects for different data types, now initialize stack top to -1, initialize stack size to 3. Step 2.1: let the object for integer is s1 Step 2.2: let the object for float is s2 Step 2.3: let the object for float is s3 Step 3: Repeat steps 4 to 8 until choice is false. Step 4: Read choice for data type into ch Step 5: If choice is 1 Step 5.1: call menu with object s1 Step 6: If choice is 2 Step 6.1: call menu with object s2 Step 7: If choice is 3 Step 7.1: call menu with object s3 Step 8: otherwise if choice is 4 Step 8.1: Exit from the program Step 9: Stop Menu Step 1: Start Step 2: Declare a variable ch to select stack operation Step 2.1: 1 is for selecting push Step 2.2: 2 is for selecting pop Step 2.3: 3 is for selecting traverse Step 2.4: return to main function Step 3: Repeat steps 4 to 7 until choice is false Step 4: If ch is 1 call push 1

Step 5: Otherwise if ch is 2 then call pop Step 6: otherwise if ch is 3 then call traverse Step 7: Otherwise exit from menu function Step 8: Stop Push: Step 1: Start Step 2: Check whether stack is full Step 2.1: If stack is full print a message that stack is full Step 2.2: Otherwise if stack is not full then do the following Step 2.2.1: Read the element to be pushed Step 2.2.2: Increment the top Step 2.2.3: Push the element into the stack Step 3: Stop Pop: Step 1: Start Step 2: Check whether the stack is empty Step 2.1: If empty then print stack is empty Step 2.2: Otherwise delete the element and decrement the top. Step 3: Stop

Traverse: Step 1: Start Step 2: Check whether the stack is empty Step 2.1: If empty print stack is empty Step 2.2: Otherwise display the elements from index 0 to top. Step 3: Stop

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> #define max 3 // template<class t> class stack { int stk[max]; public: int top; stack() { top=-1; } void push() { if(top==max-1) /* for pushing elements in to stack */ cout<<"\n stack is full"; else { int item; cout<<\nRead the element to be pushed; cin>>item; top++; stk[top]=item; } } void pop() /* for popping elements from stack */ { int i; if(top==-1) { cout<<"\n stack is empty"; } else { i=stk[top]; top--; cout<<"\n popped element is"<<i; } } void traverse() /* to display elements of stack */ { if(top==-1) cout<<Stack is Empty; else { for(int j=0;j<=top;j++) cout<<stk[j]<<"\t"; } } static void menu() /* function for calling stack operations */ { int ch; while(1) { cout<<\nSelect the stack operation;

cout<<"\n1.push 2.pop 3.traverse.otherwise go to main function"; cout<<ch; switch(ch) { case 1:push(); break; case 2:pop(); break; case 3:traverse(); break; default: break; } } }; } void main() { int ch; clrscr(); stack<int>s1; stack<float>s1; stack<char>s3; while(1) { cout<<\nSelect the data type; cout<<1.INT 2.FLOAT 3.CHAR otherwise EXIT; cin>>ch; switch(ch) { case 1:s1.menu(); break; case 2:s2.menu(); break; case 3:s3.menu(); break; default: exit(); } } }

Input/Output: Select the data type 1.INT 2.FLOAT 3.CHAR otherwise EXIT 1 Select the stack operation 1.push 2.pop 3.traverse.otherwise go to main Stack is Empty 1.push 2.pop 3.traverse.otherwise go to main Stack is Empty 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed 10 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed 20 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed 30 1.push 2.pop 3.traverse.otherwise go to main stack is full 1.push 2.pop 3.traverse.otherwise go to main 10 20 30 1.push 2.pop 3.traverse.otherwise go to main popped element is 30

function 3 function 2 function 1 function 1 function 1 function 1 function 3 function 2

1.push 2.pop 3.traverse.otherwise go to main function 4 Select the data type 1.INT 2.FLOAT 3.CHAR otherwise EXIT 2 Select the stack operation 1.push 2.pop 3.traverse.otherwise go to main Stack is Empty 1.push 2.pop 3.traverse.otherwise go to main Stack is Empty 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed 10.1 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed 20.2 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed 30.3 1.push 2.pop 3.traverse.otherwise go to main stack is full 1.push 2.pop 3.traverse.otherwise go to main 10.1 20.2 30.3 1.push 2.pop 3.traverse.otherwise go to main popped element is 30.3

function 3 function 2 function 1 function 1 function 1 function 1 function 3 function 2

1.push 2.pop 3.traverse.otherwise go to main function 4 Select the data type 1.INT 2.FLOAT 3.CHAR otherwise EXIT 3 Select the stack operation 1.push 2.pop 3.traverse.otherwise go to main Stack is Empty 1.push 2.pop 3.traverse.otherwise go to main Stack is Empty 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed a 1.push 2.pop 3.traverse.otherwise go to main Read the element to be pushed b 1.push 2.pop 3.traverse.otherwise go to main

function 3 function 2 function 1 function 1 function 1

Read the element to be pushed c 1.push 2.pop 3.traverse.otherwise go to main function 1 stack is full 1.push 2.pop 3.traverse.otherwise go to main function 3 a b c 1.push 2.pop 3.traverse.otherwise go to main function 2 popped element is c Observations: If stack is empty and POP() operation is performed then stack underflow occurs. Element PUSH() and POP() takes place at only one end called top.

Viva: 1. How do you recognize overflow in stack? A. whenever top value=stack size-1 2. What are the advantages of using arrays in stack? A.Implementation will be easy. 3.What are disadvantages of using arrays? A.No dynamic expansion.

B) QUEUE ADT: DESCRIPTION: Queue is a linear data structure, it will be having two ends called front and rear and the possible operations are ENQUEUE(), DEQUEUE(), TRAVERSE(). The ENQUEUE() operation will be done at rear end and the DEQUEUE() will be done at the front end. ALGORITHM:

Step 1: Start Step 2: Create objects for different data types, now initialize stack top to -1, initialize stack size to 3. Step 2.1: let the object for integer is s1 Step 2.2: let the object for float is s2 Step 2.3: let the object for float is s3 Step 3: Repeat steps 4 to 8 until choice is false. Step 4: Read choice for data type into ch Step 5: If choice is 1 Step 5.1: call menu with object s1 Step 6: If choice is 2 Step 6.1: call menu with object s2 Step 7: If choice is 3 Step 7.1: call menu with object s3 Step 8: otherwise if choice is 4 Step 8.1: Exit from the program Step 9: Stop Menu: Step 1: Start Step 2: Declare a variable ch to select stack operation Step 2.1: 1 is for selecting enqueue Step 2.2: 2 is for selecting dequeue Step 2.3: 3 is for selecting traverse Step 2.4: return to main function Step 3: Repeat steps 4 to 7 until choice is false Step 4: If ch is 1 call enqueue Step 5: Otherwise if ch is 2 then call dequeue

Step 6: otherwise if ch is 3 then call traverse Step 7: Otherwise exit from menu function Step 8: Stop Enqueue: Step 1: Start Step 2: Check whether queue is full Step 2.1: If queue is full print a message that queue is full. Step 2.2: Otherwise if queue is not full then do the following Step 2.2.1: Read the element Step 2.2.2: Increment the rear Step 2.2.3: Insert the element Step 2.2.4: Stop Dequeue: Step 1: Start Step 2: Check whether queue is empty Step 2.1: If empty print queue is empty Step 2.2: Otherwise delete the element and increment front Step 3: Stop Traverse: Step 1: Start Step 2: Check whether the queue is empty Step 2.1: If empty print queue is empty Step 2.2: Otherwise display the elements from index front to rear Step 3: Stop

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> #define max 3 template<class t> class queue { t queue[max]; public: int front,rear; queue() /* initializing front and rear */ { front=0; rear=-1; } void enqueue() { if(rear==max-1) /* placing elements in to queue */ cout<<"\n queue is full"; else { t item cout<<\n enter element to be inserted; rear++; queue[rear]=i; } } void dequeue() { t i; if(front==rear+1) cout<<"\n queue is empty"; else { /* removing elements from queue */ i=queue[front]; front++; cout<<"\n deleted element is"<<i; } } void traverse() /* displaying elements of queue */ { for( int j=front;j<=rear;j++) cout<<queue[j]<<"\t"; } static void menu() /* function for calling queue operations */ { int ch; while(1) { cout<<\nSelect the queue operation; cout<<"\n1.enqueue 2.dequeue 3.traverse.otherwise go to main function"; cout<<ch; switch(ch) { case 1:enqueue(); break; case 2:dequeue();

break; case 3:traverse(); break; default: break; } }; void main() { int ch; clrscr(); queue<int>q1; queue<float>q1; queue<char>q3; while(1) { cout<<\nSelect the data type; cout<<1.INT 2.FLOAT 3.CHAR otherwise EXIT; cin>>ch; switch(ch) { case 1:q1.menu(); break; case 2:q2.menu(); break; case 3:q3.menu(); break; default: exit(); } } }

10

Input/Output: Select the data type 1.INT 2.FLOAT 3.CHAR otherwise EXIT 1 Select the queue operation 1.enqueue 2.dequeue 3.traverse.otherwise go queue is Empty 1.enqueue 2.dequeue 3.traverse.otherwise go queue is Empty 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted 10 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted 20 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted 30 1.enqueue 2.dequeue 3.traverse.otherwise go queue is full 1.enqueue 2.dequeue 3.traverse.otherwise go 10 20 30 1.enqueue 2.dequeue 3.traverse.otherwise go deleted element is 10

to main function 3 to main function 2 to main function 1 to main function 1 to main function 1 to main function 1 to main function 3 to main function 2

1.enqueue 2.dequeue 3.traverse.otherwise go to main function 4 Select the data type 1.INT 2.FLOAT 3.CHAR otherwise EXIT 1 Select the queue operation 1.enqueue 2.dequeue 3.traverse.otherwise go queue is Empty 1.enqueue 2.dequeue 3.traverse.otherwise go queue is Empty 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted 10.1 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted 20.2 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted 30.3 1.enqueue 2.dequeue 3.traverse.otherwise go queue is full 1.enqueue 2.dequeue 3.traverse.otherwise go 10.1 20.2 30.3 1.enqueue 2.dequeue 3.traverse.otherwise go deleted element is 10.1

to main function 3 to main function 2 to main function 1 to main function 1 to main function 1 to main function 1 to main function 3 to main function 2

1.enqueue 2.dequeue 3.traverse.otherwise go to main function 4 Select the data type 1.INT 2.FLOAT 3.CHAR otherwise EXIT 1 Select the queue operation 1.enqueue 2.dequeue 3.traverse.otherwise go queue is Empty 1.enqueue 2.dequeue 3.traverse.otherwise go queue is Empty 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted a 1.enqueue 2.dequeue 3.traverse.otherwise go enter element to be inserted b

to main function 3 to main function 2 to main function 1 to main function 1

11

1.enqueue 2.dequeue 3.traverse.otherwise enter element to be inserted c 1.enqueue 2.dequeue 3.traverse.otherwise queue is full 1.enqueue 2.dequeue 3.traverse.otherwise a b c 1.enqueue 2.dequeue 3.traverse.otherwise deleted element is a

go to main function 1 go to main function 1 go to main function 3 go to main function 2

1.enqueue 2.dequeue 3.traverse.otherwise go to main function 4

Observations:-

If queue is empty and dequeue operation is performed then queue underflow occurs. Enqueue operation is performed at rare end and dequeue operation is performed at front end.

Viva: 1.Define a queue A.A queue is a linear list in which insertion and deletion take place at different ends. 2.What are possible operations on queue? A.Enqueue,Dequeue,Traverse. 3.What are the advantages of using arrays in queue? A.Implementation will be easy. 4.What are disadvantages of using arrays? A.No dynamic expansion.

12

2. WRITE C++ PROGRAMS TO IMPLEMENT FOLLOWING USING SINGLY LINKED LIST(ADT) A) STACK B) QUEUE

A) STACK :
DESCRIPTION: Stack is a linear data structure, it will be having an end called top, and the possible operations are PUSH(), POP(), TRAVERSE(). PUSH() and POP() will be done at the top. We use stack in applications like conversion of expressions, parenthesis matching etc.. ALGORITHM:

Step 1: Start Step 2: Create objects for different data types, now initialize stack top to -1 Step 2.1: let the object for integer is s1 Step 2.2: let the object for float is s2 Step 2.3: let the object for float is s3 Step 3: Repeat steps 4 to 8 until choice is false. Step 4: Read choice for data type into ch Step 5: If choice is 1 Step 5.1: call menu with object s1 Step 6: If choice is 2 Step 6.1: call menu with object s2 Step 7: If choice is 3 Step 7.1: call menu with object s3 Step 8: otherwise if choice is 4 Step 8.1: Exit from the program Step 9: Stop Push: Step 1: Read the element to be pushed into item Step 2: Create a node Step 3: Assign item to data field of node Step 3.1: Assign null to next pointer of item Step 4: Check whether there is more than one node Step 5: If there is more than one node set the present node as top.

13

Pop: Step 1: Chech whether top is null Step 1.1: If yes display stack is empty Step 1.2: Otherwise delete the pop node and set the immediate bottom node to top Traverse: Step 1: Check whether top is null Step 1.1: If top is null Then display stack is empty Step 1.2: Otherwise traverse the stack from top to bottom and display the data Menu: Step 1: Choose one of the options among 1.Push 2.Pop 3. Traverse 4.Exit Step 2: Read the option into variable choice Step 2.1: If choice is push then call push(item) Step 2.2: If choice is pop then call pop() Step 2.3: If choice is traverse then call traverse()

14

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> #include<malloc.h> int ch,choice; template<class t> class stklist { struct node /* declaration of node */ { t data; struct node *next; }*temp,*top,*l; public: stklist() { top=NULL; } void push(t item) /* pushing elements */ { cout<<"enter the element to be pushed"; cin>>item; temp=(node*)malloc(sizeof(struct node)); temp->data=item; temp->next=NULL; if(top==NULL) /* checking for empty of stack*/ top=temp; else { temp->next=top; top=temp; } } void traverse() { if(top==NULL) cout<<"stack is empty\n"; else { for(l=top;l->next!=NULL;l=l->next) cout<<l->data<<" "; cout<<l->data<<"\n"; } } void pop() { t item; if(top==NULL) /* checking for empty of stack */ cout<<"stack is empty\n"; else { l=top; if(l->next==NULL) /* popping elements */ { item=l->data; l=NULL; cout<<"deleted item from stack is"<<item<<"\n";

15

} } int assign() { /* function for calling stack operations */ t item; cout<<"\n1.push\n2.pop\n3.traverse\n4.exit"; while(1) { cout<<"enter your choice"; cin>>choice; switch(choice) { case 1:push(item); break; case 2:pop(); break; case 3:traverse(); break; case 4:return 0; } } } }; void main() { stklist<int>s1; stklist<float>s2; stklist<char>s3; clrscr(); while(1) { cout<<"\n1.integer\n2.float\n3.charecter\n4.exit"; cout<<"enter datatype"; cin>>ch; if(ch==1) s1.assign(); else if(ch==2) s2.assign(); else if(ch==3) s3.assign(); else if(ch==4) exit(0); } } Input/Output: 1. Integer 2. Float

top=NULL; } else { item=top->data; cout<<"deleted item from stack is"<<item<<"\n"; top=top->next; }

16

3. Char 4. Exit Enter data type 1 Push Pop Traverse Exit Enter your choice 1 Enter the element to be pushed Enter your choice 1 Enter the element to be pushed Enter your choice 1 Enter the element to be pushed Enter your choice 3 --3---2----1---- Enter your choice 2 Deleted item from stack is 3 Enter your choice 2 Deleted item from stack is 2 Enter your choice 2 Deleted item from stack is 1 Enter your choice 2 Stack is empty Enter your choice 4 1. Integer 2. Float 3. Char 4. Exit Enter data type 3 1. Push 2. Pop 3. Traverse 4. Exit Enter your choice 1 Enter the element to be pushed Enter your choice 1 Enter the element to be pushed Enter your choice 3 --b---a---- Enter your choice 2 Deleted item from stack is b Enter your choice 2 Deleted item from stack is a Enter your choice 2 Stack is empty Enter your choice 4 1. Integer 2. Float 3. Char 4. Exit Enter data type 4 Observations:

1 2 3

a b

If stack is empty and POP() operation is performed then stack underflow occurs. Element PUSH() and POP() takes place at only one end called top.

17

Viva: 1. Define a stack A.A stack is a linear list in which insertion and deletion take place at same end. 2. What are the advantages of using linked lists in stack? A . dynamic expansion. 3. What are applications of stack? A.Paranthesis matching,towers of Hanoi

18

B) QUEUE DESCRIPTION: Queue is a linear data structure, it will be having two ends called front and rear and the possible operations are ENQUEUE(), DEQUEUE(), TRAVERSE(). The ENQUEUE() operation will be done at rear end and the DEQUEUE() will be done at the front end. ALGORITHM:

Step 1: Start Step 2: Create objects for different data types, now initialize stack top to -1. Step 2.1: let the object for integer is q1 Step 2.2: let the object for float is q2 Step 2.3: let the object for float is q3 Step 3: Repeat steps 4 to 8 until choice is false. Step 4: Read choice for data type into ch Step 5: If choice is 1 Step 5.1: call menu with object q1 Step 6: If choice is 2 Step 6.1: call menu with object q2 Step 7: If choice is 3 Step 7.1: call menu with object q3 Step 8: otherwise if choice is 4 Step 8.1: Exit from the program Step 9: Stop Menu: Step 1: Select Queue operation in to choice 1.enqueue 2.dequeue 3.traverse 4.return to main step 2: if choice is 1 select enqueue step 2: if choice is 2 select dequeue step 3: if choice is 3 select traverse step 4: if choice is 4 return to main function

19

Enqueue step 1: read the element to be inserted into item step 2: create a node called temp step 3: place item in temp step 4: if front is NULL step 4.1: temp->next=NULL step 4.2: front=rear=temp step 5: otherwise step 5.1: temp->next=NULL step 5.2: rear->next=temp step 5.3: rear=temp Traverse Step 1: if front is NULL Step 1.1: print list is empty Step 2: otherwise Step 2.1 print the elements in the queue Dequeue Step 1: if front is NULL Step 1.1: print LIST IS EMPTY Step 2: otherwise Step 2.1: item =front->data Step 2.2: print deleted item, item Step 2.3: front=front->next

20

PROGRAM: # include<iostream.h> # include<conio.h> # include<stdlib.h> # include<malloc.h> int ch,choice; template<class t> class quelist { struct link /* declaration of node */ { t data; struct link *next; }*front,*temp,*rear,*l; public: quelist() { front=rear=0; } void enqueue(t item) /* placing elements */ { cout<<"enter the item to be inserted:"; cin>>item; temp=(link *)malloc(sizeof(struct link)); temp->data=item; if(front==NULL) /* for first element*/ { temp->next=NULL; front=rear=temp; } else { temp->next=NULL; rear->next=temp; rear=temp; } } void traverse() { if(front==NULL) cout<<" *** LIST IS EMPTY ***\n"; else /* displaying elements*/ { for(l=front;l->next!=NULL;l=l->next) if(l==front) cout<<"front:"<<l->data<<" -> "; else cout<<"\n"<<l->data<<" -> "; if(l->next==NULL) cout<<"\n rear:"<<l->data<<" -> \n"; } } void dequeue() { t item; if(front==NULL) cout<<" *** LIST IS EMPTY ***\n";

21

else elements */ {

/* removing item=front->data; cout<<"deleted item from queue is:"<<item<<"\n"; front=front->next;

} } int menu() /* function for calling operations of queue */ { t item; cout<<"\n 1.ENQUEUE 2.DEQUEUE 3.TRAVERSE 4.EXIT\n"; while(1) { cout<<"enter queue operation:"; cin>>choice; switch(choice) { case 1: enqueue(item); break; case 2: dequeue(); break; case 3: traverse(); break; case 4: return 0; } } } }; void main() { quelist <int> q1; quelist <float> q2; quelist <char> q3; clrscr(); while(1) { cout<<"\n 1.INTEGER 2.FLOAT 3.CHARACTER 4.EXIT\n"; cout<<"enter data type:"; cin>>ch; switch(ch) { case 1:q1.menu(); break; case 2:q2.menu(); break; case 3:q3.menu(); break; case 4:exit(1); } } } INPUT/OUTPUT : 1.INTEGER 2.FLOAT 3.CHARACTER 4.EXIT

22

enter data type:1 1.ENQUEUE 2.DEQUEUE 3.TRAVERSE 4.EXIT enter queue operation:1 enter the item to be inserted:12 enter queue operation:1 enter the item to be inserted:29 enter queue operation:1 enter the item to be inserted:23 enter queue operation:3 front:12 -> 29 -> rear:23 -> enter queue operation:2 deleted item from queue is:12 enter queue operation:2 deleted item from queue is:29 enter queue operation:3 rear:23 -> enter queue operation:2 deleted item from queue is:23 enter queue operation:3 *** LIST IS EMPTY *** enter queue operation:4 1.INTEGER 2.FLOAT 3.CHARACTER 4.EXIT enter data type:2 **** QUEUE OPERATIONS **** 1.ENQUEUE 2.DEQUEUE 3.TRAVERSE 4.EXIT enter queue operation:1 enter the item to be inserted:1.1 enter queue operation:3 rear:1.1 -> enter queue operation:2 deleted item from queue is:1.1 enter queue operation:4 1.INTEGER 2.FLOAT 3.CHARACTER 4.EXIT enter data type:3 1.ENQUEUE 2.DEQUEUE 3.TRAVERSE 4.EXIT enter queue operation:1 enter the item to be inserted:A enter queue operation:3 rear:A -> enter queue operation:4 1.INTEGER 2.FLOAT 3.CHARACTER 4.EXIT enter data type:4 Observations:-

Viva:

If queue is empty and dequeue operation is performed then queue underflow occurs. Enqueue operation is performed at rare end and dequeue operation is performed at front end.

1. Define a queue

23

A.A queue is a linear list in which insertion and deletion take place at both ends. 2. What are the advantages of using linked lists in queue? A . dynamic expansion. 3. What are the disadvantages of using linked lists in queue? A. implementation is difficult,takes more space.

24

3. WRITE C++ PROGRAMS TO IMPLEMENT DEQUE (DOUBLE ENDED QUEUE) ADT USING DOUBLY LINKED LIST DESCRIPTION: Dequeue is a linear data structure, it will be having ends front and rear at both ends and the possible operations are ENQUEUE(), DEQUEUE(), TRAVERSE(). The ENQUEUE() operation will be done at either ends (left or right) and the DEQUEUE() will be done at either ends (left or right) ALGORITHM:

Main: Step 1: Start Step 2: Initialize lfront , rfront, lrear, rrear, lstart, rstart to null Step 3: Create objects fro different data types Step 3.1: dq1 for integer type Step 3.2: dq2 for float type Step 3.3: dq3 fro char type Step 4: Select any data and place the selection choice into variable ch Step 4.1: If ch1 is 1 call fun using dq1 Step 4.2: Otherwise if ch1 is 2 call fun using dq2 Step 4.3: Step 4.3: Otherwise if ch2 is 3 call fun using q3 Step 4.4: Exit from the program Step 5: Stop Fun: Step 1: Start Step 2: Repeat steps 3 to until choice is false Step 3: Select queue operation choice into ch1 Step 3.1: If ch1 is 1 call enqueue Step 3.2: otherwise if ch1 is 2 call dequeue Step 3.3: otherwise if ch1 is 3 call traverse Step 3.4: otherwise if ch1 is 4 exit from fun Step 4: Stop Enqueue: Step 1: Start Step 2: Read the item to be inserted Step 3: Create a node Step 4: Place the item into node

25

Step 5: Select the side(left/right) of insertion into cho Step 6: If cho is 1 Step 6.1: Insert node in left side Step 6.2: Otherwise insert node in right side Step 7: Stop. Dequeue: Step 1: Start Step 2: Chech whether dequeue is empty Step 2.1: If empty print list is empty Step 2.2: Otherwise select the side (left/right) of deletion Step 2.3: Delete the lement Step 3: Stop Traverse: Step 1: Start Step 2: Check whether queue is empty Step 2.1: Otherwise first print elements from lstart to end Next print elements from rstart to end Step 3: Stop

26

PROGRAM: #include<iostream.h> #include<conio.h> #include<malloc.h> #include<stdlib.h> int choice,ch,cho; template<class t> class dequeues { public: struct link /* declaration of structure */ { t data; struct link *next,*prev; }*lfront,*lrear,*rfront,*rrear,*lstart,*l,*rstart,*temp; dequeues() /* initialization of pointers */ { lfront=lrear=rfront=rrear=lstart=rstart=NULL; } void enqueue() { t item; cout<<"\nenter the element to be inserted\n"; cin>>item; temp=(link*)malloc(sizeof(struct link)); temp->data=item; /* intiala\ization of nodes */ temp->next=NULL; temp->prev=NULL; cout<<"\ninsert 1.left\t2.right\n"; cout<<"\nenter the side of insertion\n"; cin>>cho; switch(cho) { case 1: /* for insertion */ if(lstart==NULL) /* for first element */ { lrear=temp; lrear->next=NULL; lfront->prev=NULL; lstart=lfront=lrear; } else { l=lstart; while(l->next!=NULL) l=l->next; l->next=temp; temp->prev=l; } break; case 2: { if(rstart==NULL) rrear=temp; rrear->next=NULL;

27

} Else {

rfront->prev=NULL; rstart=rfront=rrear;

} } void dequeue() { t item; if(lstart==NULL&&rstart==NULL) cout<<"\n dequeue is empty\n"; else { cout<<"\n deletion 1.left\t2.right\n"; cin>>cho; switch(cho) /* deletion of elements */ { case 1: if(lstart==NULL) cout<<"\nleftside is empty\n"; else { item=lfront->data; cout<<"deleted item is"<<item; lfront=lfront->next; } break; case 2: if(rstart==NULL) cout<<"\n right side is empty"; else { item=rfront->data; cout<<"deleted item is"<<item; rfront=rfront->next; } break; } } } void traverse() /* displaying elements */ { if(lstart==0&&rstart==0) { if(lstart==0) cout<<"\nleft side is empty"; else

} break;

l=rstart; while(l->next!=NULL) l=l->next; l->next=temp; temp->prev=l;

28

cout<<"\nright side is empty"; } else { /* displaying if queue is non empty*/ for(l=lfront;l!=NULL;l=l->next) { if(l==lstart) cout<<"lstart:"<<l->data; else cout<<" "<<l->data<<" "; } for(l=rfront;l!=NULL;l=l->next) { if(l==rstart) cout<<"\n rstart"<<l->data; else cout<<" "<<l->data; }

} } void menu() /* function for calling quque operations */ { cout<<"\n 1.enqueue\t2.dequeue\t3.traverse\n"; while(1) { cout<<"enter your choice\n"; cin>>choice; switch(choice) { case 1: enqueue(); break; case 2: dequeue(); break; case 3: traverse(); break; case 4: exit(1); } } } }; void main() { dequeues<int>d1; dequeues<float>d2; dequeues<char>d3; clrscr(); while(1) { cout<<"\n 1.integer\t2.float\t3.char\t4.exit\n"; cout<<"enter your choice"; cin>>ch; switch(ch) { case 1: d1.menu();

29

break; case 2: case 3: } d2.menu(); break; d3.menu(); break; } } Input/Output: 1. Int 2. Float 3. Char Enter your data type 1 Insertion Deletion Display Enter your choice 1 Enter item to be inserted 10 Enter side of insertion Left 2. Right Enter your choice 1 Enter item to be inserted 20 Enter side of insertion Left 2. Right Enter your choice 1 Enter item to be inserted 30 Enter side of insertion Left 2. Right Enter your choice 3 10--20---30 Enter your choice 2 Enter side for deletion Left 2. Right Deleted item is 10 Enter your choice 2 Enter side for deletion Left 2. Right Deleted item is 20 Enter your choice 2 Enter side for deletion Left 2. Right Deleted item is 30 Enter your choice 3 Dequeue is empty Enter your choice 4 Observations: Enqueue and dequeue can be done at both ends. If double ended queue is empty and we try to do dequeue operation then it results in underflow operation. Viva: 1.Define dequeue A.It is a linear list in which elements can be added and removed at either end but not in the middle

30

2.What is input restricted dequeue? A.it is the dequeue in which insertions are allowed at only one end of the list but deletions at both ends. 3. What is output restricted dequeue? A. it is the dequeue in which deletions are allowed at only one end of the list but insertions at both ends

31

4. WRITE C++ PROGRAM TO PERFORM OPERATIONS ON BINARY SEARCH TREE A) INSERT B) DELETE C)SEARCH DESCRIPTION: - Binary Search Tree is a binary tree where all the left children of a parent are less than the parent and all the right children are greater than the parent. To insert an item we have to check the item with root node if it is greater than root then we have to insert it in the right sub-tree of the root, otherwise the item will be inserted in the left sub-tree of the root. To delete an item first we have to search the item after we have to re-organize the links of its parent and children. ALGORITHM Main: Step 1: Start Step 2: Create objects for different data types Step 2.1: b1 is the template for int data type Step 2.2: b2 is the template for float data type Step 2.2: b3 is the template for char data type Step 3: Read the data type into ch Step 4: chech choice Step 4.1: If ch is int data type then call function() with b1 template Step 4.2: If ch is float data type then call function() with b2 template Step 4.3: If ch is char data type then call function() with b3 template Step 5: Stop Function Step 1: Choose the option 1 for insertion, 2 for deletion, 3 for search 4 for quit Step 2: Read your choice (option) into ch Step 2.1: If ch is 1 then Step 2.1.1: Read the element that is to be inserted into element Step 2.1.2: Call insert() Step 2.2: Otherwise if ch is 2 then Step 2.2.1: Read the element to be deleted into element Step 2.2.2: Call delete() Step 2.3: Otherwise if ch is 3 then Step 2.3.1: Read the element to be searched into element Step 2.3.2: Call search() Step 2.4: Otherwise exit Insertion Step 1: Check whether the tree contains any nodes or not Step 1.1: If not the new node as root Step 1.2: Otherwise compare the root node with new node Step 1.2.1: If the new node value is < root node Insert new node in left subtree Step 1.2.2: Otherwise insert new node in right subtree

32

Deletion Step 1: If element is root delete the root and reconstruct the tree Step 2: Otherwise if element < root Then search for the element in left sub tree - if found delete element and reconstruct the tree Step 3: Otherwise search for the element in right subtree

33

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> int ch; template<class t> class bst { struct node { public: t data; node *left,*right; }*root; public: bst() { root=NULL; } struct node *insert(node *r,t val) /* insertion*/ { if(r==NULL) { /* insertion for first element */ r=new node; r->data=val; r->left=NULL; r->right=NULL; } else { if(r->data<val) r->right=insert(r->right,val); else r->left=insert(r->left,val); } return(r); } struct node *delet(node *r,t val) /* deletion */ { node *d,*x,*p,*i; int f=0; x=r; p=NULL; while(x!=NULL) /* searching for element to delete */ { if(x->data==val) { d=x; f=1; break; } else { if(val<x->data) { p=x; x=x->left; }

34

else {

} } if(f==0) cout<<"\nelement not found"; else /* deletion of element */ { if(d->left!=NULL&&d->right!=NULL) { p=d; i=d->left; while(i->right!=NULL) { p=i; i=i->right; } d->data=i->data; d=i; } if(d->left!=NULL&&d->right==NULL) { if(p==NULL) r=d->left; else if(d==p->left) p->left=d->left; else p->right=d->right; } if(d->left==NULL&&d->right!=NULL) { if(p==NULL) r=d->right; else if(d==p->left) p->left=d->right; else p->right=d->right; } if(d->left==NULL&&d->right==NULL) { if(p==NULL) r=NULL; else if(d==p->left) p->left=NULL; else p->right=NULL; } cout<<"\n element is deleted\n"; return r; } return 0; }

p=x; x=x->right;

35

};

void search(node *r,t val) /* searching for an element */ { if(r==NULL) cout<<"element not found\n"; else { if(val<r->data) search(r->left,val); else if(val>r->data) search(r->right,val); else cout<<"element found"; } } int function() { /* function for calling operations */ t element; clrscr(); cout<<"\nMENU\n 1.insertion 2.deletion 3.search 4.quit"; do { cout<<"\nenter your choice"; cin>>ch; switch(ch) { case 1: cout<<"\nenter the element you want to insert"; cin>>element; root=insert(root,element); break; case 2: cout<<"\nenter the element tobe deleted"; cin>>element; delet(root,element); break; case 3: cout<<"\neneter the element to be searched"; cin>>element; search(root,element); break; case 4: return 0; } }while(ch<4); return(0); } void main() { bst<int>b1; bst<char>b3; bst<float>b2; clrscr();

36

while(1) { cout<<"\n****DATA TYPE****\N 1.integer 2.float 3.character\n"; cout<<"enter data type"; cin>>ch; switch(ch) { case 1: b1.function(); break; case 2: b2.function(); break; case 3: b3.function(); break; case 4:exit(1); } } } Input/Output: Integer Float char Enter data type 1 Insertion Deletion Search Exit Enter your choice 1 Enter the element you want to insert 10 Enter your choice 1 Enter the element you want to insert 20 Enter your choice 3 Enter the element to be searched 10 Element found Enter your choice 2 Enter the element to be deleted 10 Element deleted Enter Your choice 3 Enter element to be searched 10 Element not found Enter element to be deleted 20 Element deleted Enter element to be searched 20 Element not found Observations:-

If tree is empty then deletion, search operations can not be possible.

37

Viva voce: 1. define binary search tree. A.A binary search tree is a binary tree that may be empty.A non-empty binary search tree Satisfies the following properties 1.every element has a key and no two elements have the same key 2.the keys in the left subtree of the root are smaller than the key in the root 3.the keys in the right subtree of the root are larger than key in the root 4.the left and right sub trees of the root also binary search trees

38

5. WRITE C++ PROGRAMS TO IMPLEMENT CIRCULAR QUEUE ADT USING AN ARRAY. DESCRIPTION:- Queue is a linear data structure, it will be having two ends called front and rear and the possible operations are ENQUEUE(), DEQUEUE(), TRAVERSE(). The ENQUEUE() operation will be done at rear end and the DEQUEUE() will be done at the front end. When the pointer reaches the end of the queue, on next incrementation the pointer goes to the first index, by doing this we can save memory. ALGORITHM:

Main: Step 1: start Step 2: Initialize front to 0, rear to -1 Step 3: Create objects for different types Step 3.1: Object q1 for integer type Step 3.2: Object q2 for float type Step 3.3: Object q3 for char type Step 4: Now read datatype choice into ch1. Step 4.1: If ch1 is 1 call fun using q1 Step 4.2: Otherwise if ch2 is 2 call fun using q2 Step 4.3: Otherwise if ch2 is 3 call fun using q3 Step 4.4: Exit from the program Step 5: Stop Fun: Step 1: Start Step 2: Repeat steps 3 to until choice is false Step 3: Select queue operation choice into ch1 Step 3.1: If ch1 is 1 call enqueue Step 3.2: otherwise if ch1 is 2 call dequeue Step 3.3: otherwise if ch1 is 3 call traverse Step 3.4: otherwise if ch1 is 4 exit from fun Step 4: Stop Enqueue: Step 1: Start Step 2: Check whether Circularqueue is full Step 2.1: If queue is full print a message that queue is full. Step 2.2: Otherwise if queue is not full then do the following Step 2.2.1: Read the element 39

Step 2.2.2: Increment the rear by (rear+1)%size Step 2.2.3: Increment n Step 2.2.4: Insert element Dequeue: Step 1: Start Step 2:If n is 0 Print queue is empty Step 2.1: If n is not 0 Step 2.1.1: Delete element from index front Step 2.1.2: Decrement n Step 2.1.3: Change front to (front+1)%size Step 2.1.4: Print the deleted element Step 3: Stop Traverse: Step 1: Start Step 2:If n is 0 Print queue is empty Step 2.1: If n is not 0 Step 2.1.1: Display elements between front and rear Step 3: Stop

40

PROGRAM: #include<iostream.h> #include<conio.h> #define max 5 template<class t> class queues { t queues[max]; int n; public: int front,rear; void fun() /* function for alling operations */ { int ch; front=0; rear=-1; n=0; while(1) { cout<<"\n1.insertion\n2.deletion\n3.display"; cout<<"\nenter your choice"; cin>>ch; if(ch==1) { t a; cout<<"\n enter the element to be inserted"; cin>>a; insertion(a); } else if(ch==2) deletion(); else if(ch==3) display(); else break; } } void insertion(t i) /* insertion of elements */ { if(n==max) cout<<"\nqueue is full"; else { rear=(rear+1)%max; queues[rear]=i; n++; } } void deletion() { t l; if(n==0) cout<<"queue is empty"; else

41

{ l=queues[front]; /* deletion of elements */ n--; front=(front+1)%max; cout<<"\n deleted element is"<<l; } } void display() { if(n==0) cout<<"queue is empty"; else { /* displaying elements */ for(int j=front;j<=rear;j++) cout<<queues[j]<<"\t"; } } static void menu() { cout<<"\n1.enqueue"<<"\n2.dequeue"<<"\n3.traver sal"; } void main() { int cho; clrscr(); queues<int>s1; queues<float>s2; queues<char>s3; cout<<"\n1.integer type data"<<"\n2.float type data"<<"\n3.character type data"; cout<<"\nenter your choice"; cin>>cho; if(cho==1) s1.fun(); else if(cho==2) s2.fun(); else if(cho==3) s3.fun(); }

};

42

Input/Output: 1. Int 2. Float 3. Char Enter your data type 1 Insertion Deletion Display Enter your choice 1 Enter the element to be inserted 10 Insertion Deletion Display Enter your choice 1 Enter the element to be inserted 20 Insertion 2 . Deletion 3. Display Enter your choice 1 Enter the element to be inserted 30 Insertion 2 . Deletion 3. Display Enter your choice 1 Queue if full Insertion 2 . Deletion 3. Display Enter your choice 3 10 at 0 20 at 1 30 at 2 --front 1. Insertion 2 . Deletion 3. Display Enter your choice 2 Deleted item is 10 Insertion 2 . Deletion 3. Display Enter your choice 3 20 at 1 30 at 2 -front 1. Insertion 2 . Deletion 3. Display Enter your choice 2 Deleted item is 20 Insertion 2 . Deletion 3. Display Enter your choice 3 30 at 2 --front = rear 1. Insertion 2 . Deletion 3. Display

43

Enter your choice 2 Deleted item is 30 Insertion Deletion Display Enter your choice 2 Queue is empty and deletion is not possible Insertion Deletion Display Enter your choice 3 Queue is empty Insertion Deletion Display Enter your choice 4 Observations: If queue is empty and dequeue operation is performed then queue underflow occurs. Enqueue operation is performed at rare end and dequeue operation is performed at front end. When the pointer reaches the end of the queue, on next incrementation the pointer goes to the first index

Viva:

1. Define circular queue. A. A circular queue is one in which the insertion of a new element is done at the very first Location of queue if the last location of queue is full. 2.At which end ,deletion take place in queue? A. front end.

44

6. WRITE C++ PROGRAMS USING NON-RECURSIVE FUNCTIONS TO TRAVERSE BINARY TREE A)PREORDER B)POSTORDER C)INORDER DESCRIPTION:- In preorder traversal, we first visit the root and then we traverse the left sub-tree of the root in preorder and then the right subtree in preorder. In postorder traversal, we first visit the left sub-tree of the root in postorder and then the right sub-tree traversed in postorder and finally we traverse the root of the tree. In inorder traversal, we first visit the left sub-tree in inorder and then the root of the tree and at last the right sub-tree is traversed in the inorder. ALGORITHM: Main: Step 1: Start Step 2: Create objects for different data types Step 2.1: b1 is the template for int data type Step 2.2: b2 is the template for float data type Step 2.2: b3 is the template for char data type Step 3: Read the data type into ch Step 4: chech choice Step 4.1: If ch is int data type then call function() with b1 template Step 4.2: If ch is float data type then call function() with b2 template Step 4.3: If ch is char data type then call function() with b3 template Step 5: Stop Function: Step 1: Read the operation as 1 for insert 2 for inorder 3 for preorder 4 for postorder 5 for delete 6 for exit Step 2: Read the choice ch Step 2.1: If the choice is 1 Read the element to be inserted into element Step 2.2: Call insert Step 3: Otherwise ch is 2 Step 3.1: Call inorder function Step 4: Otherwise if ch is 3 Step 4.1: Call preorder function Step 5: Otherwise if ch is 4 Step 5.1: Call postorder Step 6: Otherwise if ch is 5 Step 6.1: Call deletion Step 7: Otherwise Step 7.1: Exit

45

Insertion Step 1: Check whether the tree contains any nodes or not Step 1.1: If not the new node as root Step 1.2: Otherwise compare the root node with new node Step 1.2.1: If the new node value is < root node Insert new node in left subtree Step 1.2.2: Otherwise insert new node in right subtree

Deletion Step 1: If element is root delete the root and reconstruct the tree Step 2: Otherwise if element < root Then search for the element in left sub tree - if found delete element and reconstruct the tree Step 3: Otherwise search for the element in right subtree Inorder Step 1: Start from root Step 2: If this is the only node in the tree display it Step 3: Otherwise Step 3.1: Traverse the left sub tree in inorder Step 3.2: Display root Step 3.3: Traverse the right sub tree in inorder Preorder Step 1: Start from root Step 2: If this is the only node in the tree display it Step 3: Otherwise Step 3.1: Display root Step 3.2: Traverse the left sub tree in Preorder Step 3.3: Traverse the right sub tree in Preorder Postorder Step 1: Start from root Step 2: If this is the only node in the tree display it Step 3: Otherwise Step 3.1: Traverse the left sub tree in Postorder Step 3.2: Traverse the right sub tree in Postorder Step 3.3: Display root

PROGRAM:

46

#include<iostream.h> #include<conio.h> #include<stdlib.h> int top=-1,top1=-1,ch; template<class t> class bst { struct node /* definig structure for node */ { public: t data; node *left,*right; }*root,*a[20],*b[20]; public: bst() { root=NULL; } struct node *insert(node *r,t val) { if(r==NULL) /* insertion for first element */ { r=new node; r->data=val; r->left=NULL; r->right=NULL; } else { if(r->data<val) r->right=insert(r->right,val); else r->left=insert(r->left,val); } return(r); } struct node *deletion(node *r,t val) { node *data,*d,*x,*p,*i; int f=0; x=r; p=NULL; cile(x!=NULL) { if(x->data==val) /* search for element to delete */ { d=x; f=1; break; } else if(val<x->data) { p=x; x=x->left; } else {

47

} } if(f==0) cout<<"\n element not found"; else /* deletion of element */ { if(d->left!=NULL && d->right!=NULL) { p=d; i=d->left; while(i->right!=NULL) { p=i; i=i->right; } d->data=i->data; d=i; } if(d->left!=NULL && d->right==NULL) { if(p==NULL) r=d->left; else if(d==p->left) p->left=d->left; else p->right=d->right; } if(d->left==NULL && d->right!=NULL) { if(p==NULL) r=NULL; else if(d==p->left) p->left==NULL; else p->right=NULL; } cout<<"\n elements deleted "; return(r); } } void inorder_non_rec(node *r) /* inorder traversal */ { node *l; l=r; do { while(l!=NULL) { push(l); l=l->left; } while(top>-1) { l=pop(); cout<<" "<<l->data; if(l->right!=NULL) {

p=x; x=x->right;

48

} else } }while(l!=NULL);

l=l->right; break; l=NULL;

} void preorder_non_rec(node *r) /* for pre order traversal */ { node *l; l=r; do { cout<<" "<<l->data; if(l->right!=NULL) push(l->right); l=l->left; if(l==NULL && top>-1) l=pop(); }while(l!=NULL); } void postorder_non_rec(node *r) /* for post order traversal */ { node *l; l=r; do { while(l!=NULL) { push(l); if(l->right!=NULL) { push(l->right); b[++top1]=l->right; } l=l->left; } do { l=pop(); if(l!=b[top1]) cout<<" "<<l->data; else { top1=top1-1; break; } }while(top>-1); }while(l!=NULL && top>-1); }

49

void push(node *r) /* function for pushing */ { top=top+1; a[top]=r; } struct node *pop() /* function for popping */ { return a[top--]; } int function() /* function for calling operations */ { t element; cout<<"\nmenu \n 1 insert 2 inorder 3 preorder 4 post order 5 delete 6 exit\n"; do { cout<<"\n enter ur choice "; cin>>ch; switch(ch) { case 1:cout<<"\n enter element to be inserted:"; cin>>element; root=insert(root,element); break; case 2:cout<<"\n rec inorder traversal:"; inorder_non_rec(root); break; case 3:cout<<"\n rec preorder traversal :"; preorder_non_rec(root); break; case 4:cout<<"\n rec post order traversal:"; postorder_non_rec(root); break; case 5:cout<<"\n enter element to be deleted :"; cin>>element; deletion(root,element); break; case 6:return(0); } }while(ch<6); } }; void main() { bst<int>b1; bst<float>b2; bst<char>b3; clrscr(); while(1) { cout<<"\n data type \n 1 int 2 float 3 char 4 exit \n"; cout<<"enter data type \n"; cin>>ch; switch(ch) {

50

case 1:b1.function(); break; case 2:b2.function(); break; case 3:b3.function(); break; case 4:exit(1); } } getch();

INPUT/OUTPUT : Data type Integer Float Character Exit Enter data type 1 Menu Insert Inorder Preorder Postorder Delete Exit Enter your choice 1 Enter element to be inserted 5 Enter your choice 1 Enter element to be inserted 3 Enter your choice 1 Enter element to be inserted 8 Enter your choice 1 Enter element to be inserted 2 Enter your choice 1 Enter element to be inserted 7 Enter your choice 1 Enter element to be inserted 9 Enter your choice 2 Rec inorder traversal 2 3 5 7 8 9 Enter your choice 3 Rec preorder traversal 5 3 2 8 7 9 Enter your choice 4 Rec postorder traversal 2 3 7 9 8 5 Enter your choice 5 Enter the element to be deleted 5 Element deleted Enter your choice 2 Rec inorder traversal 2 3 7 8 9 Enter your choice 6 Data type Integer Float Character Exit Observations:-

51

If tree is empty then deletion, traversing operations can not be possible.

VIVA:1. Define binary tree A.Binary tree is a tree in which every element has exactly two sub trees when it is not empty. 2.Write preorder notation for the expression a*b+c/d. A.+*ab/cd 3.Write post order notation for expression a+x+y/+b*c*a A.a-xy++b+ca**/.

52

7. WRITE C++ PROGRAMS FOR THE IMPLEMENTATION OF BFS AND


DFS FOR A GIVEN GRAPH. DESCRIPTION:- First we visit the a node of the graph and then we traverse all the children of that node i.e., at the same level. After this, we repeat the same process until the graph is fully traversed. BFS ALGORITHM:

MAIN: Step 1: Start Step 2: Create an object for int data type Step 3: using the obj call the function fun() Step 4: Stop Fun( ): Step 1: Read the number of vertices into n Step 2: Read the value of vertices into array ver[i] Step 3: Initialize visit[i] to 0 (means declaring all vertices are not visited] Step 4: Read the adjacency matrix of the graph into adj[i][j] Step 5: Now enter or read the key element to be searched into key Step 6: Step 6.1: Compare the root with the key Step 6.1.1: If they are equal Print key element if found in the graph Step 6.1.2: Otherwise compare the vertices which are in the next level with key & if found then print element found Step 6.1.3: Repeat 6.1.2 for all levels of the three until element found or all the vertices in the tree are visited

53

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> template<class t> class bfs { public: t adj[80][80],i,j,n,k,f,r,q[80],visit[80]; t ver[80],key; void fun() { cout<<"\n enter number of vertices:"; cin>>n; cout<<"\n enter name of vertices\n"; for(i=1;i<=n;i++) { cin>>ver[i]; /* giving names*/ visit[i]=0; } cout<<" enter the adjaceny matrix form of the graph:"; for(i=1;i<=n;i++) for(j=1;j<=n;j++) cin>>adj[i][j]; cout<<"\n enter key elment to be searched"; cin>>key; k=2; f=1; r=1; if(ver[1]==key) /* if searching element is first element */ { cout<<"key element is found in graph"; getch(); exit(0); } else { /* searching for element */ q[r++]=1; while(k<=n) { i=q[f++]; for(j=1;j<=n;j++) { if(adj[i][j]==1&&visit[j]==0) { if(ver[j]==key) { cout<<"element found"; getch(); exit(0); } Else /*marking the node */ { visit[j]=1;

54

q[r]=j; r++; k++; } } } } cout<<"key not found"; getch(); exit(0);

} }; }

void main() { bfs<int>b1; b1.fun(); clrscr(); getch(); }

55

INPUT/OUTPUT: Enter number of vertices:4 1 2 3 4 Enter the Adjacency Matrix of the graph 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 Enter the key element to be found 5 Key not found Observation: Whenever the graph is empty, the key element can not be found. The key node should be with in the range of vertices.

Viva voce: 1.Which data type is used in implementation of BFS? A. queue 2.Draw BFS for the following figure A.

56

Ans.

1 3 6 8

57

DFS
THEORY:- First we visit the a node of the graph and then we traverse the nodes hierarchically i.e.,level by level. After this, we repeat the same process until the graph is fully traversed. DFS ALGORITHM

Step 1: Start Step 2: Read number of vertices Step 3: Read the adjacency matrix Step 4: Enter element to be searched into key Step 5: Compare key with root node Step 5.1: If they are equal print element is found and then quit Step 5.2: Otherwise go to the node in the next in the level Step 5.3: Repeat Step 5.2 either step 5.1 is met or till you reach to last level Step 5.4: Visit the immediate predicersor and visit its children Step 5.5: Check for 5.1 if failed Step 5.5.1: Repeat Step 5.4 to Step 5.5 until 5.1 is true or all nodes are visited Step 6: Stop

58

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> template <class t> class dfs { public: t i,j,l,n,k,visit[80],q[80],adj[80][80]; t ver[80], key; void fun() { cout<<"\n enter number of vertices:\n"; cin>>n; cout<<"\nenter name ofvertices"; for(i=1;i<=n;i++) { /* giving names */ cin>>ver[i]; visit[i]=0; } cout<<"enter the adjacencymatrix form of the graph"; for(i=1;i<=n;i++) for(j=1;j<=n;j++) cin>>adj[i][j]; cout<<"\n enter key element to be searched"; cin>>key; if(ver[1]==key) /* if first elemnt is searching element */ { cout<<"key element is found in given graph"; getch(); exit(0); } else { q[l]=l; /* searching for element */ visit[l]=l; } k=2; l=2; while(k<=n) { i=--l; for(j=1;j<=n;j++) { if(adj[i][j]==1&&visit[j]==0) { if(ver[j]==key) { cout<<"element found"; getch(); exit(0); } else {

59

visit[j]=1; /* marking the node */ q[l]=j; l++; k++; i=j; } } } } cout<<"key not found"; getch(); exit(0); } }; void main() { dfs<int>d1; d1.fun(); clrscr(); getch(); }

60

INPUT/OUTPUT: Enter number of vertices:4 1 2 3 4 Enter the Adjacency Matrix of the graph 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 Enter the key element to be found 5 Key not found Observation: VIVA: 1. 1.Which data type is used in implementation of DFS? A. stack 2.Draw BFS for the following figure A. Whenever the graph is empty, the key element can not be found. The key node should be with in the range of vertices.

61

ANS.

1 3 6 8

62

8. WRITE C++ PROGRAMS FOR IMPLEMENTING SORTING METHODS A)QUICK B)MERGE C)HEAP QUICK SORT: DESCRIPTION:Quick sort is an algorithm of type divide and conquer.That is the problem of sorting a set is reduced to problem of sorting two smaller sets.On an average, time complexity is o(nlogn). ALGORITHM

Quick(a,n,beg,end,loc) Step 1: [Initialize] set left :=beg, rigkt :=end and loc := beg Step 2: [scan from right to left.] a) Repeat while a[loc] < a[right] and loc notequal to right [ End of loop] b) If loc = right, then: return. c) If a[loc]>a[right], then: i) [Interchange a[loc] and a[right].] Temp := a[loc], a[loc] := a[right],a[right] := temp ii) Set loc := right iii) Go to step 3. [ End of if structure] Step 3: [Scan from left to right] a) Repeat while a[left]< a[loc] and left notequal to loc: Left := left +1 [ End of loop] b) If loc = left, then :return c) If a[left]>a[loc], then i) [Interchange a[left] and a[loc].] Temp := a[loc], a[loc] := a[left],a[left] := temp ii) Set loc := left iii) Go to step 2 [ End of if structure] (Quicksort) Step 1: [ Initialize ] top := null Step 2: [ Push boundary values of a onto stacks when a has 2 or more elements.] If n>1, then : top = top + 1, lower[1] :=1, upper[1] ;=n. Step 3: Repeat steps 4 to 7 while top notequal to null. Step 4: [ Pop sublists from stacks] Set beg :=lower[top], end :=upper[top], Top = top -1

63

Step 5: Call quick(a, n, beg, end, loc) [ procedure 6.5] Step 6: [ Push left sublist onto stacks when it has 2 or more elements.] If beg <loc -1, then: Top := top + 1, lower[top] := beg Upper[top] := loc-1 [ End of if structure] Step 7: [ Push right sub list onto stacks when it has 2 or more elements.] If loc +1 < end, then: Top := top +1, lower[top] := loc +1 Upper[top] := end [ End of if structure] [ End of step 3 loop] Step 8: exit

64

PROGRAM: #include<iostream.h> #include<stdlib.h> #include<conio.h> void quick(int,int); int a[100]; void main() { int i,n,lo,hi; clrscr(); cout<<"enter no.of elements"; cin>>n; cout<<"enter elements"; for(i=0;i<n;i++) cin>>a[i]; /* reading elements */ lo=0; hi=n-1; quick(lo,hi); cout<<"sorted elements are:\n"; for(i=0;i<n;i++) cout<<a[i]<<"\t"; getch(); } void quick(int l,int h) /* using quick sort */ { int i,j,pivot,pin,t; i=l+1; j=h; pivot=a[l]; pin=l; if(l<h) { do { while(a[i]<pivot&&i<=h) i++; while(a[j]>pivot&&j>=l) j--; if(i<j) { /* swapping */ t=a[j]; a[j]=a[i]; a[i]=t; } }while(i<j); t=a[pin]; a[pin]=a[j]; a[j]=t; quick(l,j-1); quick(j+1,h); } }

65

INPUT/OUTPUT: Enter the Number of Elements:5 Enter the Elements into Array:100 60 40 30 90 Sorted Order is 30 40 60 90 100 Observations: The number of elements should not exceed the size of the array.

VIVA : 1.What is the worst case time complexity of quick sort? A. o(n2) 2.What is the best case time complexity of quick sort? A.o(nlogn) 3. What is the average case time complexity of quick sort? A.o(nlogn)

66

MERGE SORT DESCRIPTION:Merge sort states that the given list can be broken into smallerlists and then merged together.Initially we consider that the list is broken into two pieces.The various steps that will be carried out will be as follows: 1.Divide the list into half. 2.Sort the left half. 3.sort the right half. 4.Merge the two sorted halves into one sorted list. ALGORITHM:

Mergepass(a, n, l, b) Step 1: Set q := int(n/2*l)) , s:= 2 * l *q and r:= n s Step 2: [ Use procedure 9.5 to merge the qpairs of subarrays] Repeat for j=1,2,------------,q: a) Set lb := 1+(2*j -2) *l [ Finds lower bound of first array] b) Call merge(a, l, lb, a, l, lb+l, b, lb) [ End of loop] Step 3: [Only one sub array left?] If r<l, then: Repeat for j=1,2------------r: Set b( s + j ) := a(s + j) [ End of loop] Else Call merge(a, l, s+1, a, r, l+s+1, b, s+1) [ end of if structure ] Step 4: Return Mergesort( a, n ) Step1 : Set l:=1.[ Initializes the number of elements in the subarrays] Step 2: Repeat steps 3 to 6 while l<n: Step 3: Step 4: Step 5: Call Mergepass( a, n, l, b) Call Mergepass( b, n, 2*l, a) Set L:= 4 * l [ End of step 2 loop]

Step 6: Exit

67

PROGRAM: #include<iostream.h> #include<conio.h> void mergesort(int,int); void merge(int,int,int); int a[10],b[10]; void main() { int i,n,lo,hl; clrscr(); cout<<"enetr no.of elemnets :"; cin>>n; cout<<"enetr elements into array"; for(i=0;i<n;i++) cin>>a[i]; /*reading elements */ lo=0; hl=n-1; mergesort(lo,hl); cout<<"sorted elements are:\n"; for(i=0;i<n;i++) cout<<"\t"<<a[i]; getch(); } void mergesort(int l,int h) { int mid; if(l<h) { mid=(l+h)/2; /* breaking array into two parts */ mergesort(l,mid); mergesort(mid+1,h); merge(l,mid,h); } } void merge(int l,int mid,int h) { int i,j,k,hl; i=l; j=mid+1; k=l; while(i<=mid&&j<=h) { if(a[i]<a[j]) { b[k]=a[i]; i++; } else { b[k]=a[j]; j++; } k++; } if(i>mid) /* finding largest element from two parts */ { for(hl=j;hl<=h;hl++)

68

b[k++]=a[hl]; } else if(j>h) { for(hl=i;hl<=mid;hl++) b[k++]=a[hl]; } for(k=l;k<=h;k++) a[k]=b[k]; } INPUT/OUTPUT: Enter the Number of Elements:5 Enter the Elements into Array:100 60 40 30 90 Sorted Order is 30 40 60 90 100 Observations: The number of elements should not exceed the size of the array.

VIVA : 1.when does the worst case time complexity occur in merge sort? A. when elements are in decreasing order. 2.which design paradigm is used in merge sort? A.Divide and Conquer

HEAP SORT DESCRIPTION:

69

Heap sort algorithm consists of two phases. 1.Build a heap H out of the elements of A. 2.Repeatedly delete the root element of H If H is a max heap ,then 2nd phase gives list of elements in descending order else if it is a min heap,gives elements in ascending order. ALGORITHM:

Insheap(tree, n, item) Step 1: [ Add new node to h and initialize ptr] Set n := n+1 and ptr := n Step 2: [ Find location to insert item] Repeat steps 3 to 6 while ptr <1 Step 3: Set par := [ptr/2]. [location of parent node] Step 4: If Item < tree[par], then: Set tree[ptr]

70

PROGRAM: #include<iostream.h> #include<conio.h> int x[10],i,n; void heap(int); void maxheap(int); void main() { clrscr(); cout<<"enter no of elements"; cin>>n; cout<<"enetr the elements"; for(i=1;i<=n;i++) cin>>x[i]; /* reading elements */ heap(n); cout<<"sorted elements are:"; for(i=1;i<=n;i++) cout<<x[i]<<"\t"; } void heap(int n) { int t; while(n>1) { maxheap(n); /* calling max heap */ t=x[1]; x[1]=x[n]; x[n]=t; n=n-1; } } void maxheap(int n) { int i,t,j; for(i=2;i<=n;i++) { t=x[i]; j=i; while(x[j/2]<t&&j>1) { x[j]=x[j/2]; j=j/2; } x[j]=t; } }

71

INPUT/OUTPUT: Enter the Number of Elements:5 Enter the Elements into Array:100 60 40 30 90 Sorted Order is 30 40 60 90 100 Observations: The number of elements should not exceed the size of the array.

VIVA :1.what is the time complexity of this algorithm? A.o(nlogn) 2.What is max heap? A.The root node value will be greater than its child nodes. 3.What is min heap? A.The root niode value will be less than its child nodes.

72

9. WRITE C++ PROGRAM TO PERFORM THE FOLLOWING OPERATIONS ON B-TREE A) INSERTION B) DELETION Description: A B-tree of order m is an m-way search tree.If the B-tree is not empty, the corresponding extended tree satisfies the following properties: 1.the root has at least two children. 2.all internal nodes other than the root have at least [m/2] children. 3.all external nodes are at the same level. Algorthim: Program: #include<iosstream.h> #include<fstream.h> #include<stdlib.h> #include<string.h> #include<conio.h> const long Nilptr=-1l; typrdef char String Type[49]; typrdef char keyFieldType[13]; typedef char dataFielstype[37]; typedef struct { Keyfieldtypekeyfield; Datafieldtype datafield; }item type; Class Tablebaseclass { Public: Virtual int empty(void)=0; Virtual int Insert(const Item Type&item)=0; Virtual int retrieve(keyfield type searchkey,itemType&itme)=0; Protected: Fstream dataFile; Long numitems; Char openMode; }; Typedef struct { int count; Item type key[4]; Long branch[5]; }nodetype; Void error(char *msg); Class BTTabteclass:public TableBasec1<lss { public: BTTableClass(char Mode,char *filename); ~BTTableClass(void); Int Empty(void); Int insert(const itemtype&item); Int retrieve(keyfieldtype serach key,item type&item); Void details(void); Void check(void); Private:

73

Void checksubtree(long current,keyfieldtype&last); //for debugging Int serchnode(const keyfieldtype target&new item,long new right, nodetype &node, int location) Void Additem(const itemtype&new item); Void spjjtf(const itemtype &cur~enuuem,long current right,long current root,int location,itemtype&new item,long &new right); Void pushdown(const item type&current item,long current root,int&lowerup,itemtype&(N~witemi long&.newright); Long root; Long nqmnodes; Int nodesize; Node type current node;

}; Void error(char *msg) { Cerr<<msg<<end1; Exit(0); } Void BTTableClass::Details(void) { Int k; Long p; Cout<<end1<<root is node( record) number<<root<<end1; For(p=0;p<=nrimnodes;p++) { If(p%4=3) { Cout<<presenter; Cin.get(); } datafile.seek(p*nodesize,ios::beg); Datafile.read((char*)(&currentnode),nodesize); If(p=0) { cout<<details\n; Cout<<--------------------------\n; Cout<<node 0 is not part of tree , contains this dasta:<<end1; Cout<<numnodes=<<current node.branch[1]<<end1; Cout<<root<<currentNode.Branch[2]<<end1; } Else { Cout<<-----------------\n; Cout<<details of node number<<p<<end1; Cout<<count:currentnode:count<<end1; Cout<<---------------------------\n; Cout<<keys:; For(k=0;k<currentnode.count;k++) Cout<<currentnode.branch[k]<< ; Cout<<end1<<end1; } } } Void BTTableClass::check(void)

74

{ keyFieldType last; last[0]=*; last[1]=NULL; chaecksubtree(Root,Last); } Void BTTableClass::CheckSubtree(long current, keyFieldtype&last) { nodeType node; int k; if(current==nilptr) return; dataFile.seekg(current*nodeSize,ios::beg); datafile.read<<char*)(&node),nodesize); for(k=0;k<node.count;k++) { Checksubtree(node.brancjh[k],last); If<<last[0]!=*)&&(strcmp(last,node.key[k].keyfield;=9>> { Cout<<check has found a problem in node<<current-<< index<<k<<key<<node.key[k]field<<end1;exirt(1); } Strcpy(last,node.key[k].keyfield); } Checksubtree(node.branch[node.count],last); } BTTableclass::BTTableclass(char mode,char *filename) { Openmode=mode; Nodesize=sizeof(nodeType); If(mode==r) { Datafile.open(filename,ios::in ios::binary); If(datafile.fail0) Error(file cannot be opened); Datafile.read<<char *)(&currentNode),nodeSize); If(datafile.fail0) { //assume the btrees empty if you cannot read from file Nurnitems=0; Numnodes=0; Root=nilptr; } Else//node zero is not a normal node,it contains the following: { Numitems=currentnode.branch[0]; Numnodes=currentnode.branch[1]; Root=currentnode.Branch[2]; } } Else if(mode ==w) { Datafile.open(Filename,ios::in||ios::out|ios::trunc|ios::binary); If(datafile.fail0) Error(file cannot be opened); Root=nilptr; Numitems=0; Numnodes=0;//number does not include the special node zero Currentnode.branch[0]=numitems;

75

} Details(); Datafile.close(); } Int Bifable class::empty(void) {//we could read node zero,but this is faster: Return(root==nilptr); } Int BTTableclass::searchnode(const keyfieldtype target,int &location)const { Int found;

Currentnode.branch[1]=numnodes; Currentnode.branch[2]=root; Datafile.seekp(0,ios::beg); Datafile.writ((char *)(&currentnode),nodesize);

Found=0; If(strcmp(Target,CurrentNode.key[0].keyfield)<0) Location=-1; Else { //do a sequential search,right to left: Location=CurrentNode.Count-1; While(strcmp(Target,CurrentNode.Key[Location].KeyField)<0)&&(Location>0)) Location--; If(strcmp(Target,CurrentNode.Key[Location].KeyField)==0) Found=1; } return Found; } Void BTTableClass::AddItem(const ItemType & NewItem,long NewRight, NodeType&Node,int Location) { int j; for(j=Node.Count;j>Location;j--) { Node.Key[0]=Node.Key[j-1]; Node.Branch[j+1]=Node.Branch[j]; } Node.Key[Location]=NewItem; Node.Branch[Location+1]=NewRight; Node.Count++; } Void BTfableclass::split(const ItemType && CurrentItem, long CurrentRight, long CurrentRoot, int Location, ItemType & NewItem, long & NewRight) { Int j,Median; Node Type RightNode; If(Location<1) Median=1; Else Median=1+1; DataFile.seeking(CurrentRoot * NodeSize, ios::beg); DataFile.read<<char*)(&CurrentNode), NodeSize); For(j=Median;j<4;j++) { //move half of the items to the right node RightNode.Key[j-MedianJ=CurrentNode.Key[j]; RightNode.Branch[jMedian+1] CurrentNode.Branch[j+1];

76

} RightNode.count=4.Median; CurrentNode.Count=Median; //is then incremented by addItem if location<1 Add.Item(CurrentItem,CurrentRi4ht.CurrentN9de, Location +1); Else Add.Item(CurrentItem,CurrentRi4ht.CurrentN9de, Location Median+1); NewItem=CurrentNode.I<key[CurrentNode.Branch{currentNode.Count]; CurrentNode.Count--; DataFile.seekp(CurrentRoot*NodeSize,io::beg); DataFile.write<<char *)(CurreNOde), NodeSize); NumNodes++; NewRight= NumNodes; } Void BTTableClass::PushDown(const ItemType & CurrentItem, longf CurrentRoot, int & MoveUp, ItemType & NewItem, long &NewRight) { Int location; If(CurrentRoot==NilPtr)//stooping case { //cannot insert into emp tree MoveUp=1; NewItem=CurrentItem; NewRight=NilPtr; } Else { DataFile.seekg(CurrentRoot * NodeSize,ios::beg); DataFile.read<<char *)(& CurrentNode),NodeSize); If(SearchNode(CurrentItem.KeyField,Location>> Error(Error:attempt to put a duplicate into B-tree); PushDown(CurrentItem, CurrentNode.Branch[Loation+1], Move Up, NewItem, NewRight); If(MoveUp) { DataFile.seekg(CurrentRoot * NodeSize,ios::beg); DataFile.read((char *)(& CurrentNode),NodeSize); } Else { MoveUp=1; Split(NewItem, NewRight.CurrentRoot,Location, NewItem,NewRight); } } } } Int BTTableClass::Insert(const ItemType & Item) { int MoveUp; long NewRight; ItemType NewItem; PushDown(Item, Root, MoveUp, NewItem, Newright); If(MoveUp)//create a new root node { CurrentNode.count; CurrentNode.Key[0]= NewItem;

77

CurrentNode.Branch[0]= Root; CurrentNode.Branch[1]; NumNo(!es++); Root NumkNodes; DataFile.seekup(NumNodes *NodeSize, ios :: beg); DataFile.write(char *)(&CurrentNode),NodeSize); } NumItems++; return 1; } Int BTTableClass::Retrieve(KeyFieldType SearchKey, ItemType & Item) { long CummtRoot; int Found; CurrentRoot= Root; while((CurrentRoot!=NilPtr) && (!found)) { Datafile.seekg(CurrentRoot * NodeSize, ios::beg); DataFile.read(char *)(&CurrentNode), NodeSize); if(SearchNode(SearchKey, Location)) { Found=1; Item=CurrentNode.Key[location]; } else CurrentRoot= CUJrentNode.Branch[Location+1]; return Found; } int MyGetLine(IsStream & Instream, char *String1, int String MCIJ) { char Chi; int Co~t,last; Count=0; Last=StringMax; Ch= InStream.get(); while((Cb!=\n &7 (Cb!=InStream:fail())) { if(Count<Last) String1[Count++]= Chi; Ch=InStream.get(); String1[Count]= NULL; return(Count); } } void ReadLine(fstream & InputFile, KeyFieldType word,DataFieldType Definition) { char Line[40]; int k,Chi; MyGetLine(InputFile, Line, 49); for(k=0;k<12;k++) word[k]=NULL; for(k=0;k<36;k++) {

78

Ch=Line[12+k]; if(Ch==\n) break; Definition[k]=ch; } Definition[k]=NULL; cout<<Line<<\t\t<<Definition; } void Load(fstream &InputFile, BTTableClass &Table) { ItemType Item; int Count; Count=0; ReadLine(InputFile, Item.KeyField, Item.DataField); while(!InputFileJail()) { Count++; if(Count==24) { cout<<end1<<press enter; cin.get(); } if(strcmp(Item.KeyField,END)=0) return; else { TableInsert(Iter0); cout<<\n; } Table.CheckO; ReadLine(InputFile, Item.KeyField, Item.DataField); } } void main() { fstre s01.irce; clrscr(); BTTableClass(w,sri.data); Source.open(siva.txt,ios::in); if(SourceJail()) { cout<<ERROR: Unable to open file BTREE<<end1; exit(1); } cout<<-------------------------c \n; cout<<person<<\t\tIdentity<<end1; cout<<-------------------------\n<<n; Load(Source,BTTable); cout<<Entered; Source.close(); }

Input file:
79

VIVEKANANDA GANDHI KALAM HITECH SRIDHAR RANJANI Output: PERSON VIVEKANANDA philosopher GANDHI National Leader KALAM Favorite Person HITECH Publishers SRIDHAR FIRST Author RANJANI Second Author

Our Philosopher Our National Leader My Favorite Person Publishers FIRST Author Second Author IDENTITY Our Philosopher Our National Leader My Favorite Person Publishers FIRST Author Second Author

Our Our My

Call of destructor Root is node(record) number 3 Details Node 0 is not part of tree, contains this data: Num items=6 Num nodes=3 Root=3 Details of node number 1 Count:1 Keys: GANDHI Branches: -1 -1
80

Details of node number 2 Count: 4 Keys: KALAM RANJANI --SRIDHAR VIVEKANANDHA BRANCHES: -1 -1 -1 -1 -1 Press enter Details of node number 3 Count: 1 Keys: HITECH Branches : 12 CC
Viva : 1.say 1 condition when the full node is splitted. Ans: when the new element needs to go into a full node,the ful node is splitted. 2.what is the number of disk accesses needed for insertion? Ans: h+2s+1

81

10. WRITE C++ PROGRAM TO PERFORM OPERATIONS ON AVL-TREE A) INSERTION B) DELETION THEORY:- A binary tree is an AVL tree if every node in the tree is having a balance factor either -1, 0 or 1. By doing the operations like insertion() or deletion(), an imbalance in the tree may occur. Then we have to re-organize the tree in such a way that it satisfies the properties of an AVL tree. ALGORITHM:

MAIN Step 1: Start Step 2: Create an object Step 2.1: Set root to null Step 2.2: Set root1 to null Step 3: Select the operation 1. Insertion 2. Find 3. Deletion 4. Height 5. Exit Step 4: Read the operation into choice Step 5: If choice = 1 Step 5.1: Read inserting node into a Step 5.2: Call insert() Step 6: Otherwise if choice is 2 Step 6.1: Read node to be searched into findele Step 6.2: If the tree contains atleast one element then call find() Step 7: Otherwise if ch is 3 Step 7.1: Enter the element to be deleted into delete Step 7.2: Call the delete() Step 7.3: Display the tree Step 7.4: Call inorder() Step 8: Otherwise choice = 4 Step 8.1: Find the height & depth of the tree by calling avlheight() Step 8.2: Display no of nodes by calling nonodes() Step 9: Otherwise choice=5 Exit from program Step 10: Stop

Insert 82

Step 1: If the tree doesnot contain any node then make present node as root and set its Two links to null and set height to 0 Step 2: If Step1 fails compare a with root Step 2.1: If a<root then Insert a to the left of root Step 2.2: Find balance factor and check if 2 Step 2.2.1: If 2.2 is true check if a<p->left->element then SingleRotateLeft(p) Otherwise P = DblRotateleft(p) Step 2.3: If a>root then Insert a to the right of root Find: Step 1: If p =null Step 1.1: Print element not found Otherwise Step 1.2: If a<p then Search for a in left subtree Step 1.3: Otherwise if a>p then Search for a in right subtree Step 1.4: Otherwise print a is found Delete: Step 1: If p = null then Print element not found Step 1.1: Otherwise if a<p then Check for a in left sub tree If found delete a Step 1.2: Otherwise if a>p then Check for a in right sub tree If found delete a Step 1.3: Otherwise if a=p Delete p Height: Step 1: If p =null then Return -1 Step 1.1: Otherwise assign p-->height to t Step 1.2: Return t

83

Single Rotation left: Step 1: Create nodeptr p2 Step 2: p2 = p1 --> left Step 3: p1 ----> left = p2 -right Step 4: p2 --- right = p1 Double Rotation Left: Step 1: p1 left = SingleRotateRight(p1 left) Step 2: Return SingleRotateLeft(p1) Single Rotation Right: Step 1: p2 = p1 right Step 2: p1 right = p2 left Step 3: p2 left = p1 Double Rotation Right: Step 1: p1 right = SingleRotateLeft(p1 right) Step 2: Return SingleRotateRight

84

PROGRAM: #Include<iostream.h> #Include<conio.h> #Include<stdlib.h> struct node { /* defining node */ int element; node *left; node *right; int height; }; typedef struct node *nodeptr; template<class T> class avltree { public: void insert(T,nodeptr &); /* defining functions */ void del(T,nodeptr &); void find(T,nodeptr &); int avlheight(nodeptr); }; template<class T> void avltree<T>::insert(T x,nodeptr &p) { if(p==NULL) { p=new node; p->element=x; /* for first element */ p->left=NULL; p->right=NULL; p->height=0; if(p==NULL) cout<<Out of Space; } else { if(x<p->element) { /* traversing for insertion */ insert(x,p->left); if((avlheight(p->left)-avlheight(p->right))==2) { if(x<p->left->element); p=singlrotaleft(p); else p=dblrotaleft(p); } } else if(x>p->element) { insert(x,p->right); if((avlheight(p->right)-avlheight(p->left))==2) { if(x<p->right->element); p=singlrotarght(p);

85

} } else }

else p=dblrotarght(p);

cout<<Element Already Exists<<x; int m,n,d; m=avlheight(p->left); n=avlheight(p->right); d=max(m,n); p->height=d+1;

} template<class T>

void avltree<T>::del(T x,nodeptr &p) { nodeptr d; if(p==NULL) cout<<Element Not Found; else if(x<p->element) del(x,p->left); /* searching element to delete */ else if(x>p->element) del(x,p->right); else if((p->left==NULL)&&(p->right==NULL) { d=p; free(d); p=NULL; cout<<Element Deleted; } else if(p->left==NULL) { d=p; free(d); /* freeing the memeory */ p=p->right; cout<<Element Deleted; } else if(p->right==NULL) { d=p; p=p->left; free(d); cout<<Element Deleted; } else p->element=deletemin(p->right); } template<class T> void avltree<T>::find(T x,nodeptr &p) { /* finding an element */ if(p==NULL) cout<<Element Not Found; else

86

if(x<p->element) find(x,p->left); else if(x>p->element) find(x,p->right); else cout<<Element found; } int avltree<T>::avlheight(nodeptr p) { Int t; if (P==Null) Return -1 else { T = pheight Return t; } } int main() { clrscr(); Nodeptr root,root1,min,max; Int a,choice,findele,delete,leftele,rightele,flag; Char ch=y; AV Ltree<int>bst; Root=NULL; Root1=NULL; Do { Cout<<\t\t---------------------------------------------------\n; Cout<<\t\t AVL TREE\n; Cout<< 1.INSERTION \n; Cout<< 2.DELETION \n; Cout<< 3.FIND \n; Cout<< 4 Height \n; Cout<< 5.EXIT \n; Cout<<\t ----------------------------------------------------\n; Cout<<enter the choice:; Cin>>choice; Switch(choice) { Case 1: While(1) { Cout<<inserting node; Cin>>a; If(a==-1) break; Bst.insert(a,root); /* calling for insertion */ Cout<<endl; } Case 2: Cout<<\t delete node; Cin>>delete;

87

Bst.del(delete, root); /* calling for deletion */ break; Case 3: Cout<< \t search node:; Cin>> findele; /* calling for

finding an element*/

If(root!=null) Bst.find(findele,root); Cout<<\n; Break; Case 4: Cout<<height and depth; Cout<<bst.avlheight(root); Cout<, \n no of nodes:<<bst.nonodes(root); Cout<<\n; Break; Case 5: Exit(0); Default: cout<<Invalid choice<<endl; } }While(1); }

88

INPUT/OUTPUT: Output #1: --------------------------------------------------AVLTREE ---------------------------------------------------1.INSERTION 2.DELETION 3.FIND 4. Height ---------------------------------------------------Enter The Choice:1 Inserting Inserting Inserting Inserting Inserting Inserting Inserting Inserting Inserting Inserting Inserting Inserting Inserting Node:5 Node:3 Node:1 Node:4 Node:29 Node:9 Node:7 Node:25 Node:31 Node:27 Node:12 Node:13 Node:-1

AVL Tree After Insertion of Above Elements

Output #2: --------------------------------------------------AVLTREE ---------------------------------------------------1.INSERTION 2.DELETION 3.FIND 4. Height 5. Exit ----------------------------------------------------

Enter Your Choice:2 Delete Node:12 Output #3: --------------------------------------------------AVLTREE ---------------------------------------------------1.INSERTION

89

2.DELETION 3.FIND 4. Height 5. Exit ---------------------------------------------------Enter Your Choice:3 Search node:27 Output #4: --------------------------------------------------AVLTREE ---------------------------------------------------1.INSERTION 2.DELETION 3.FIND 4. Height 5. Exit ---------------------------------------------------Enter The Choice:4 Height and depth :3 No of nodes:1 Observations:-


VIVA :-

If tree is empty then deletion,find operations can not be possible. If tree is empty then height function returns -1.

1.What is height of AVL tree with n nodes? A.o(logn) 2.What is balance factor of a node x? A. height of left subtree - height of right sub tree

90

11. WRITE C++ PROGRAM TO IMPLEMENT KRUSKALS ALGORITHM TO GENERATE A MINIMUM SPANNING TREE. DESCRIPTION: For finding the minimum spanning tree using Krushkals algorithm, first we have to solve the graph according to the edges weights ( in ascending order). Then we add edge by edge (i.e., starting from minimum edge) and if the added edge forms a cycle we neglect the edge. In this way, we can add all the edges from the sorted list if they do not create any cycle. ALGORITHM:

Algorithm krushkal(e, cost, n,t) { Construct a heap out of the edge costs using heapify; For i=1 to n do parent[i]:=-1; //Each vertex is in a different set i:=0; mincost:=0.0; while((i<n-1) and (heap not empty) ) do { Delete a minimum cost edge(u, v) from the heap and reheapify using adjust; J:=find(u); k:=find(v); If(j notequal k) then { I := i+1 T[I,1] := u; t[I,2] :=v; Mincost := mincost + cost[u,v]; Union(j,k); } } If(I notequal to n-1) then write ( nospanning tree) Else Return mincost; } Algorithm union(i,j) { Temp := p[i] +p[j]; If ( p[i] >p[j]) then { P[i] := j; p[j]:= temp; } Else { P[j]:=I; p[i]:=temp; } }

91

PROGRAM: #include<iostream.h> #include<conio.h> #include<stdlib.h> #define n 6 #define m 15 int u[20]; template<class T> class krushkal { private: t weight[20][20]; int vertex; t e[m][3]; t f[n-1][3]; int totedges; public: krushkal(int n) { vertex=n; } void read(void); void sort(void) void display(void) void initializeedge(void); void displayedge(void); void makeset(int i); int find(int i); void merge(int p, int q); int equal(int p, int q); void initial(void); void test_univ(void); void findspan(void); void spandisplay(void); void pause(void); void initialspan(void); }; template<class T> void krushkal<T>.::read(void) { int w1; /* reading elements */ t w; cout<<enter the no of vertex; cin>>w1; vertex=w1; for(int i=0;i<vertex;i++) for(int j=0;j<vertex;j++) weight[i][j]=0; for(i=0;i<vertex;i++) { for(int j=0;j<vertex;j++) { if(i==j) weight[i][j]=0; else {

92

} } } }

if(weight[i][j]=0) /* adding weight */ { cout<<i+1<<to<<j<<edge weight; cin>.w; weight[i][j]=weight[j][i]=w; }

template<class T> void krushkal<T>::makeset(int i) { u[i]=i; } template<class T> int krushkal<t>::find(int i) { int j; /* for finding element */ j=i; while(u[j]!=j) j=u[j]; return j; } template <class T> void krushal<T>::merge(int p, int q) { if(p<q) u[q]=p; else u[p]=q; }

template<class T> int krushkal<T>::equal(int p, int q) { if(p==q) return(1); else return(0); }

template<class T> void krushkal<T>::initial() { int i; for(i=0;i<vertex;i++) makeset(i); }

93

template<class T> void krushkal<T>::test_univ(void) { int i; cout<<the disjoint subsets are:\n; for(i=0;i<vertex;i++) cout<< <<u[i]; cout<<\n; } template<class T> void krushkal<T>::display(void) { /* displaying elements */ int i,j; cout<<weight matrix\n; for(i=0;i<vertex;i++) { for(j=0;j<vertex;j++) if(weigh[i][j]==99 cout<<*; else cout<<weight[i][j]<< ; cout<<\n; } } template<class T> void krushkal<T>::pause(void) { int i; cout<<press enter to continue.\n; getch(); } template<class t> void krushkal<t>::initializeedge(void) { int k=0; for(int i=0;i<vertex;i++) { for(int j=0;j<vertex;j++) if(j>i)&&(weight[i][j]!=99) { e[k][0]=i; e[k][1]=j; e[k][2]=weight[i][j]; k++; } } totedges=k; } template<class T> void krushkal<t>::displayedge(void) { for(int i=0;i<totedges;i++) { for(int j=0;j<3;j++) cout<< <<e[i][j]; cout<<\n;

94

} } template<class T> void krushkal<T>::sort(void) { int i,j,a,b,c; cout<<no of edges<<totedges; for(i=totedges-1;i>0;i__) { for(j=0;j<i;j++) if(e[j][2]>e[j+1][2] { a=e[j][0]; a=e[j][1]; a=e[j][2]; e[j][0]=e[j+1][0]; e[j][1]= e[j+1][1]; e[j][2]= e[j+1][2]; e[j+1][0]=a; e[j+1][1]=b; e[j+1][2]=c; } } }

template<class T> void krushkal<T>::initialspan(void) { for(int i=0;i<vertex-1;i++) for(int j=0;j<3;j++) f[i][j]=-1; } template<class T> void krushkal<T>::findspan(void) { int num_edges=0; int next_edge=0; int a,b,c,i,j; while(num_edges<vertex-1) { a=e[next_edge[0]; b=e[next_edge[1]; j=find(b); if(!equal(i,j)) { merge(i,j); f[num_edges[0]=e[next_edge[0]]; f[num_edges[1]=e[next_edge[1]]; f[num_edges[2]=e[next_edge[2]]; num_edges++; test_univ(); } next_edge++; }

95

} template<class T> void krushkal<T>::spandisplay(void) { t weight=0.0; cout<<\n minimal spanning tree edges:\n; cout<<f=(; for(int i=0;i<vertex-1;i++) { cout<<(v<<f[i][0]+1<<v<< f[i][1]+1<<); if(i<vertex-2) cout<<,; weight=weight+fi][2]; } cout<<)n; cout<<minimal spanning tree weight:<<weight<<endl; } int main() { clrscr(); krushkal<int>h(10); h.read(); h.display(); h.initializeedge(); h.displayedge(); h.sort(); h.initialspan(); h.initial(); h.test_univ(); h.findspan(); h.spandisplay(); return(0); }

Input/output: enter the no of vertex 8 1 to 2 edge weight 34 1 to 3 edge weight 12 1 to 4 edge weight 99 1 to 5 edge weight 99 1 to 6 edge weight 99 1 to 7 edge weight 99 2 to 3 edge weight 99 2 to 4 edge weight 99 2 to 5 edge weight 7 2 to 6 edge weight 99 2 to 7 edge weight 99 2 to 8 edge weight 44 3 to 4 edge weight 99 3 to 5 edge weight 15 3 to 6 edge weight 20 3 to 7 edge weight 99 3 to 8 edge weight 99 4 to 5 edge weight 99 4 to 6 edge weight 13

96

4 4 5 5 5 6 6 7

to to to to to to to to

7 8 6 7 8 7 8 8

edge edge edge edge edge edge edge edge

weight weight weight weight weight weight weight weight

10 99 99 99 99 11 8 5

weight matrix 0 34 12 ** ** ** ** ** 34 0 ** 7 ** ** 44 ** 12 ** 0 15 20 ** ** ** ** 7 15 0 13 10 ** ** ** ** 20 13 0 ** ** 11 ** ** ** 10 ** 0 9 8 ** 44 ** ** ** 9 0 5 ** ** ** ** 11 8 5 0 no of edges 12 the disjoint subsets are: 01234567 the disjoint subsets are: 01234566 the disjoint subsets are: 01214566 the disjoint subsets are: 01214556 the disjoint subsets are: 01214156 the disjoint subsets are: 01211156 the disjoint subsets are: 01011156 the disjoint subsets are: 00011156 minimal spanning tree edges: f=((v7,v8),(v2,v4),(v6,v8),(v4,v6),(v5,v8),(v1,v3),(v3,v4)) minimal spanning tree weight:68 Observations:For finding the minimum spanning tree, the graph will be sorted according to its edges weights. VIVA :-

97

1.What is the total asymptotic complexity? A.o(n+eloge) 2.Which design paradigm in used in kruskals algorithm? A.Greedy method.

98

12. WRITE C++ PROGRAM FOR IMPLEMENTING KNUTH-MORRIS PRATT PATTERN MATCHING. DESCRIPTION:- KNUTH-MORRIS PRATT is a pattern matching algorithm which can have better efficiency than BRUTE-FORCE algorithm and BOYER-MOORE algorithms. Here its efficiency is taken by the number of comparisions. Here to minimize the number of comparisions, we use a function called failure function. ALGORITHM:

Kmpmatch(String Str, String Patteren) Begin F = failure(Pattern) i=0 j=0 while i<n if str[i] = pattern[j] then if j= m-1 then found , return i-j else i= i +1 j = j+1 end if else if j>0 j = failure[j-1] else i=i+1 end if while end Return -1 End Algorithm for computation of Failure function f(0) = 0 i=1 j=0 while i<m if pattern[i] = pattern[j] then f(i) = j +1 i = i+1 j = j +1 else if (j>0) then j= f(j-1) else f(j)=0; i = i+1 end if while end

99

PROGRAM: #include<string.h> #include<stdlib.h> #include<conio.h> #include<iostream.h> class kmp { char *str; int index; int *restr; public: kmp(char *, int=-1); ~kmp() { delete str; delete restr; } void reset() { index=0; } int match(char c); }; char *store(char * s, int slen=-1) { if(s==0) return 0; if(slen<0) slen=strlen(s); char *new_s=new char[slen+1]; if(new_s==0) return 0; memcpy(new_s,s,slen); new_s[slen]=\0; return new_s; } static int *shift(char *str) { if(str==0) return 0; int *restr=new int[strlen(str)+1]; if(restr==0) return 0; restr[0]=-1; for(int i=0;str[i]!=\0;i++) { restr[i+1]=restr[i]+1; while(restr[i+1]>0&7str[i]!=str[retr[i+1]-1]) restr[i+1]=restr[restr[i+1]-1]+1; } return restr; } kmp::kmp(char * t,int tlen) { str=store(t,tlen); restr=shift(str); index=0; }

100

int kmp::match(char c) { if(restr==0) return 0; while(c!=str[index]) { if(index==0) return 0; index=restr[index]; } else { index=restr[index]; return 1; } } void main() { char *c; char *s= ; cout<<enter string; cin>>s; cout<<patteren to find; cin>>c; kmp m(c,-1); m.reset(); for(;*s!=\0;s++) { if(m.match(*s)) { cout<<string:<<c<,found\n; getch(); exit(0); } } cout<<string:<<c<<not found\n; getch(); }

101

Input/Output:Enter String: AGACGAGACAGATGA Patteren to find: CGAGA String CGAGA Found Observations:If the pattern is not present in the given text then unsuccessful search will result. Viva voice:1.why do we go for KMP algorithm? Ans : Specifically we perform many comparitions while testing a potential placement of pattern against the text,yet if we discour a pattern character that does not match with text then we throw all the informations gained by these comparisions and start the comparision of the next element.Kmp avoids this waste of time. 2.what is the complexity of KMP? Ans : O(n+m) 3.How can a failure function in the KMP is defined? Ans : IT is the length of the longest prefix of P that is suffix of P[1..j]

102

13. WRITE C++ PROGRAM TO IMPLEMENT ALL THE FUNCTIONS OF A DICTIONARY (ADT) USING HASHING. DESCRIPTION: Hashing is one of the methods for dictionary implementation. Here we map the dictionary keys into hash table by using hash index. We prefer mostly the division hash function. If D is number of buckets in the hash table K is the key element then the hash function f(K)=K%D. Here the f(K) is called home bucket. If two keys are having same home bucket then we say that a collision has occured. ALGORITHM:

Main Step 1: Start Step 2: Create an object h with bucket size 11 Step 3: Select the dictionary operation 1. Insert 2. Remove 3. Search 4. Display 5. Exit Step 4: Repeat stepd 5 to until choice is false Step 5: Read the operation into choice Step 6: If choice =1 then Step 6.1: Read element to be inserted Step 6.2: Call insert() Step 7: Otherwise if choice =2 then Step 7.1: Read element to be deleted Step 7.2: Call remove() Step 8: Otherwise if choice=3 then Step 8.1: Read element to be searched into k Step 8.2: Now check h.search(k,e)==-1 Print not found Step 8.3: If 8.2 fails Print element found at Index,h.search(k,e) Step 9: Otherwise if choice = 4 Call display Step 10: Otherwise if choice =5 Exit from the program Step 11: Stop

103

Insert(): Step 1: check if k is in dictionary Step 2: If Step 1 is true Print bad input or no memory Step 3: If step 1 is failed Insert k in appropriate bucket b Where b=bsearch(k). Remove(): Step 1: Assign the location ok k into b Where b = hsearch(k) Step 2: Now delete k from hash table Search(): Step 1: assign the location of k into b Where b=bserach(k) Step 2: Check whether the hash table index b contains k or if it empty Step 2.1: If it is empty return -1 Step 2.2: Otherwise if k is in hash table return b Display(): Step 1: Print the hash table elements Step 2: Assign 0 to i Step 3: Repeat steps 4 to 5 until i=0 Step 4: If empty[i] print 0 Step 5: Otherwise print ith element in hash table

104

PROGRAM: #include<iostream.h> #include<conio.h> class quad { int a[10]; int num; int key; public: void quadprobe() { int i,j; for(i=0;i<10;i++) a[i]=0; while(1) /* reading elements */ { cout<<"insert element (-1 to stop)"; cin>>num; if(num==-1) return; key=num%10; if(a[key]==0) a[key]=num; else { /* placing the elements */ i=1; j=key; while(a[j]!=0) { j=key+(i*i)%10; i=i+1; } if(a[j]==0) a[j]=num; } } } void quaddisp() /* displaying elements */ { for(int i=0;i<10;i++) cout<<a[i]<<" "; cout<<"\n"; } }; void main() { clrscr(); quad q; cout<<"elements in quadaratic probing--\n"; q.quadprobe(); q.quaddisp(); }

105

INPUT/OUTPUT: Elements in Quadratic Probing--Insert element(-1 To Stop):12 Insert element(-1 To Stop):13 Insert element(-1 To Stop):14 Insert element(-1 To Stop):15 Insert element(-1 To Stop):16 Insert element(-1 To Stop):17 Insert element(-1 To Stop):-1 0 0 12 13 14 15 16 17 0 0 Observations: If the number of inserted elements increases then overflow occurs.

VIVA :1.say one application of hashing. Ans:it is used in dictionary implementation. 2.when the collision occurs? Ans:when 2 keys have same hash bucket then collision occurs.

106

Additional Aim: To implement friend functions Description:To make an outside function friendly to a class ,and have to simply declare this function as a friend to the class.It will be not in the scope of the class to which it has been declared as friend.Since it is not in the scope of the class it can not be called using the object of that class .It can be invoked like a normal function without the help of thee class. Algorithm: Class abc Step1:start Step2:constructor abc a)read the d value step3:stop class xyz Step1:start Step2:constructor xyz a)read the i value Step3:declare the max function as friend function. Step4:stop Algorithm: max Step1:start Step2: input object of abc and xyz Step4:a)if a.d is grater than x.i i)write the gratest number as a.d b)else ii)write the gratest number as x.i Step5:stop Alogorithm :main Step1:start Step2:call max function with parameters as objects of abc and xyz Step3:stop.

Program: /*********** program to implement friend functions***************/

#include<conio.h> class xyz; class abc { int d; public: abc() //To initialize the variables { cout<<enter the value of d :; cin>>d; }; class xyz { int i; public: xyz() //To initialize the variables

107

{ cout<<enter the value of i :; cin>> i; } friend void max(abc a,xyz x); }; //definition of max function void max(abc a,xyz x) { if(a.d>=x.i) cout<<greatest number is :<<a.d; else cout<<greatest number is :<<x.i; } void main() { clrscr(); abc a1; xyz x1; max(a1.x1); getch(); } Input/output: enter value of d: 4 enter value of i:5 greatest number is :5
VIVA-VOICE:

1.In which mode should a friend function be declared? Ans:It can be declared either in public or private mode. 2.Can we acces the member functions of the class in friend functions? Ans: we can not call it directly .Ae should use the objects to call them. 3.What is the syntax of friend function? Ans: friend returntype functionname(parameters)

108

Overloading: Aim:To implement Overloding Description:To define an additional tasks an operator we must spesy what it means in relation to the class which the operator is applied .This is done with the help of a special function,called operator function,which describes the task. Algorithm: Class ABC Step1:start Step2:Define the constructor ABC a)Initialize A,B,Cwith values 10,-30,45 Step3:definition of function display a)write a,b,c Step4:Void operator (); Step5:stop Define operator function for Step1:start Step2:assign A=-a and B=-b and C=-c Step3:stop Algorithm :main Step1:start Step2:call s.display(); Step3:do -s; Step4:write values after unary operator overloading by s.display Step:Stop Program: /*******to implement operator overloading**********/ #include<iostream.h> #include<conio.h> Class ABC { Int a,b,c; Public: ABC()//to initialize variables { A=10; B=-30; C=45; } Void display()//definition of function display { Cout<<\n<<a=<<a; Cout<<\n<<b=<<b; Cout<<\n<<c=<<c; }

109

Void operator (); }; //definition of operator function Void ABC::operator () { A=-a; B=-b; C=-c; } Void main() { ABC s; Clrscr(); s.display(); -s; Cout<<\n<<values after unary operator overloading; s.display(); getch(); } Output: A=10; B=-30 C=45 Values after unary operator overloading: A=-10 B=30 C=-45
VIVA-VOICE:

1. what is the general form of an operator function? Ans: returntype classname:: operator op(arg_list) { Return body } 2. what is the difference between function overloading and operator overloading? Ans: Over loading of function is function overloading and overloading of an operator is operator overloading.

110