Ads a Lab Manual

Embed Size (px)

Citation preview

  • 8/13/2019 Ads a Lab Manual

    1/90

    DEPARTMENT OF INFORMATION TECHNOLOGY

    ADVANCED DATA STRUCTURES & ALGORITHMS LAB

    Prepar By

    Mr. T.BhaskarAsst Prof (cse dept)

    SRI VENKATESWARA COLLEGE OF ENGINEERING & TECHNOLOGYRVS NAGAR, CHITTOOR

  • 8/13/2019 Ads a Lab Manual

    2/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 2

    Contents

    1) Write C++ program to implement the following using an arraya) Stack ADT b) Queue ADT

    2) Write C++ programs to implement the following using a singly linked list

    a) Stack ADT b) Queue ADT

    3) Write C++ program to implement the dequeue (double ended queue) ADT using a doubly

    linked list

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

    a) Insert element into a binary search tree.

    b) Delete an element from a binary search tree

    c) Search for a key element in a binary search tree

    5) Write a C++ program to implement circular queue ADT using an array

    6) Write a C++ programs that use non-recursive functions to traverse the given binary tree in

    a) Preorder b) in order c) post order

    7) Write a C++ programs for the implementation of bfs and dfs for a given graph

    8) Write C++ programs for implementing that following sorting methods:

    a) Quick sort b) Merge sort c) Heap sort

    9) Write a C++ program to perform the following operations

    a) Insertion into a B-tree b) Deletion from B-tree

    10) Write a C++ program to perform the following operations

    a) Insertion into an AVL tree b) Deletion from an AVL tree

    11) Write a C++ program to implement kruskals algorithm to generate a minimum spanning tree

    12) Write a C++ program for implement prims algorithm to generate a minimum spanning tree

    13) Write a C++ program to implement all the functions of a dictionary (ADT) using hashing

  • 8/13/2019 Ads a Lab Manual

    3/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 3

    TABLE OF CONTENTS

    S.NOTITLE(List of programs) PAGE NO

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    a) Stack ADT b) Queue ADT using an array

    a) Stack ADT b) Queue ADT using SLL

    Dequeue ADT using a doubly linked list

    Insert Delete Search operations in binary search

    Circular queue ADT using an array

    a) Preorder b) in order c) post order

    BFS and DFS for a given graph

    a) Quick sort b) Merge sort c) Heap sort

    a) Insertion into a B-tree b) Deletion from B-treea) Insertion into an AVL tree b) Deletion from an

    AVL tree

    implement kruskals algorithm to generate a

    minimum spanning tree

    Prims algorithm to generate a minimum

    spanning tree

    implement all the functions of a dictionary (ADT)

    using hashing

    (additional program)

    Binary Tree Traversal using Recursion

    6-12

    13-19

    20-23

    24-30

    31-34

    35-42

    43-48

    49-53

    54-58

    59-69

    70-71

    72-74

    75-81

    82-90

  • 8/13/2019 Ads a Lab Manual

    4/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 4

    C++ Programming Language:

    1. The C++ programming language is the advancement to the normal procedure

    oriented languages like COBOL, FORTRAN, C etc.2. In case of the object oriented programming (OOP) languages like C++ the datadoesnt flow freely around the system where as it is viewed as a sequence ofthings such as reading, calculating and printing in case of procedure orientedlanguages. Data flow freely around the system in this case.

    3. The OOP allows decomposition of a problem into number of entities calledobjects and builds data and functions around the objects. The procedureoriented consists of writing a list of instructions. These instructions groupinginto functions.

    4. This OOP deals with the real world problems where as procedure orienteddoesnt model real world problems very well.

    5. The principles of the OOP are Encapsulation, Data Abstraction, Inheritance,Polymorphism, and Dynamic Binding etc.

    Applications of C++:

    C++ is a versatile language for handling very large programs. It is suitable forvirtually any programming task including development of editors, compilers,databases, communication systems and any complex real-life application systems.

    1. Since C++ allows us to create hierarchy-related objects, wecan build special object-oriented libraries, which can beused later by many programmers.

    2. While C++ is able to map the real-world problem properly,the C part of C++ gives the language the ability to get closeto the machine-level details.

    3. C++ programs are easily maintainable and expandable. Whena new feature needs to be implemented, if is very easy toadd to the existing structure of an object.

    4. It is expected that C++ will replace C as a general-purposelanguage in the near future.

    C++ Compiler:

    1 The file can be stored in C++ like .cpp & .cxx.2. Here we use CC command to compile the program like cc.example.c3. The source code available in example.c4. The compiler would produce an object file example.o and then automatically

    link with the library functions to produce an executable file.5. Executable file name is a.out.

  • 8/13/2019 Ads a Lab Manual

    5/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 5

    C++ Compilation:1. Create and save the source files using under the file options.2. Edit them under the Edit option.

    3. Compile the program under the compile option and execute it under the Runoption.4. The Run option can be used without compiling the source code. In this case, the

    Run command causes the system to compile, link and run the program in onestep.

    5. A program spread over multiple files can be compiled as cc file1.c file2.06. The statement compiles only the file file1.c and links with previously compiled

    file2.07. This is useful when only one of the files needs to be modified. The files that

    arent modified need not be compiled again.

    Sample Program:

    #include#includevoid main(){

    cout

  • 8/13/2019 Ads a Lab Manual

    6/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 6

    Problem Statement:Write a C++ Programs to implement the following using an Array

    a) Stack ADTb) Queue ADT

    a) Solution Design:Design a class named stack which has member variables top, an array s [], ele, ch, I.All member variables have to be global. Design 3 public methods, one to push theelements into the stack; second one to pop from stack and the third is to display theelements in the stack.

    Class Name:StackProperties/Member Variables:int top=-1, ele, ch, I, s [];Constructors: None.

    Public Interface:void push (), pop (), display ();Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Creates a Stack object.2. Calls the method push () on the above object and pushes the element into the

    stack, calls method pop () to pop the elements out of the stack and the methoddisplay () to display the elements from the stack.

    3. If the stack is full when pushing, this method prints Stack overflow, if stack isempty when popping, this displays Stack underflow, and if to display when noelements are present in the stack, this displays that the stack is empty.

    Test Cases:Test 1:Enter the choice for 1.push 2.pop 3.displayInput: ch=1Expected Output: enter the element to pushInput: n=5Test 2:

    Input: ch=1Expected Output: enter the element to pushInput: n=3Test 3:Input: ch=3Expected Output: the elements are: 3 5

    Test 4:

  • 8/13/2019 Ads a Lab Manual

    7/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 7

    Input: ch=2Expected Output: deleted element is 3

    Reference Implementation:####################################################################File: stack.cpp

    #include#include#include#define max 5int top=-1,s[max],ele,ch,i;templateclass stack{public:

    void push(void);

    void pop(void);void display(void);};

    templatevoid stack::push(void){if(top==max-1){cout

  • 8/13/2019 Ads a Lab Manual

    8/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 8

    top--;}}

    template

    void stack::display(void){if(top==-1){cout

  • 8/13/2019 Ads a Lab Manual

    9/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 9

    Execution:Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

    Possible Enhancements:

    The size of the array can be dynamically created instead of creating itstatically. Whenever an overflow condition arises instead of displaying themessage we can add a method that can create the double size of the array asbefore to insert the overflowed element.

    b) Solution Design:Design a class named Queue1 which has r, f, ele, q [max],ch,i as member variables. Allmember variables have to be global. Design 3 public methods, one to insert theelements into the queue, second to delete the elements from the queue, and theother to display the elements in the queue.

  • 8/13/2019 Ads a Lab Manual

    10/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 10

    Class Name:Queue1Properties/Member Variables:int r=0, f=0, ele, q [max], ch, iPublic Interface:void insert (), void delete (), void display ()Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create the queue1 object.2. Calls the method insert () to insert the elements into the queue, method del () to

    delete the elements from the queue and the method display () to display theelements from the queue.

    3. If inserted values exceed the max value of queue It displays queue overflow, ifto delete from empty queue it displays queue underflow and if to display theelements from empty queue it displays queue is empty.

    Test Cases:Test 1:Enter the choice for 1.insert 2.delete 3.displayInput: ch=1Expected Output: enter the element to insertInput: n=5Test 2:Input: ch=1Expected Output: enter the element to elementInput: n=3

    Test 3:Input: ch=3Expected Output: the elements are: 3 5Test 4:Input: ch=2Expected Output: deleted element is 3

    Reference Implementation:####################################################################File: queue1.cpp

    #include

    #include#include#define max 5int r=0,f=0,ele,q[max],ch,i;templateclass queue1{public:

  • 8/13/2019 Ads a Lab Manual

    11/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 11

    void insert();void del();void display();};

    templatevoid queue1::insert(void){if(r==max){cout

  • 8/13/2019 Ads a Lab Manual

    12/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 12

    }}

    int main(){

    clrscr();queue1q;while(ch

  • 8/13/2019 Ads a Lab Manual

    13/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 13

    Problem Statement:Write a C++ Programs to implement the following using an singly linked list

    a) Stack ADTb) Queue ADT

    a) Solution Design:Design a class Stlink which has a structure node to represent a linked list which is aglobal. Create 2 links temp, top. All these variables are global. Design 3 publicmethods, one to push the elements into the stack; second one to pop from stack andthe third is to display the elements in the stack.

    Class Name: StlinkProperties/Member Variables: temp, topPublic Interface: void push (), pop (), display ().

    Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create a stlink object.2. Calls the method push () on the above object and pushes the element into the

    stack, calls method pop () to pop the elements out of the stack and the methoddisplay () to display the elements from the stack.

    3. If the stack is full when pushing, this method prints Stack overflow, if stack isempty when popping, this displays Stack underflow, and if to display when no

    elements are present in the stack, this displays that the stack is empty.

    Test Cases:Test 1:Enter the choice for 1.push 2.pop 3.displayInput: ch=1Expected Output: enter the element to pushInput: n=5Test 2:Input: ch=1

    Expected Output: enter the element to pushInput: n=3Test 3:Input: ch=3Expected Output: the elements are: 3 5Test 4:Input: ch=2Expected Output: deleted element is 3

  • 8/13/2019 Ads a Lab Manual

    14/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 14

    Reference Implementation:File: stlink.cpp

    #include#includestruct node{int info;struct node *link;}*p,*temp,*top=NULL;templateclass stlink{public:

    void push(void);

    void pop(void);void display(void);};

    templatevoid stlink::push(void){int n;p=new node;coutlink=top;top=p;}templatevoid stlink::pop(void){if(top==NULL)cout

  • 8/13/2019 Ads a Lab Manual

    15/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 15

    temp=top;while(temp!=NULL){cout

  • 8/13/2019 Ads a Lab Manual

    16/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 16

    b) Solution Design:Design a class queue1 which has structure queue as global. It is used to represent alinked list. The members of this structure are data, next. Create 2 links front, rear.Design 3 public methods, one to insert the elements into the queue, second to deletethe elements from the queue, and the other to display the elements in the queue.

    Class Name:Queue1Properties/Member Variables:rear, front, nextPublic Interface:void insert (), void del (), void display ()Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.1. Create the queue1 object.

    2. Calls the method insert () to insert the elements into the queue, method del () todelete the elements from the queue and the method display () to display the elementsfrom the queue.3. If inserted values exceed the max value of queue It displays queueoverflow, if to delete from empty queue it displays queue underflow and if todisplay the elements from empty queue it displays queue is empty.

    Test Cases:Test 1:Enter the choice for 1.insert 2.delete 3.displayInput: ch=1

    Expected Output: enter the element to insertInput: n=5Test 2:Input: ch=1Expected Output: enter the element to elementInput: n=3Test 3:Input: ch=3Expected Output: the elements are: 3 5Test 4:Input: ch=2

    Expected Output: deleted element is 3

    Reference Implementation:

  • 8/13/2019 Ads a Lab Manual

    17/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 17

    ####################################################################File: QLL.cpp

    #include#include#includestruct queue{int data;struct queue *next;}*p,*rear=NULL,*front=NULL,*temp;templateclass queue{public:

    void insert(void);void del(void);

    void display(void);};templatevoid queue::insert(void){int x;coutx;p=new queue;p->data=x;p->next=NULL;

    if(front==NULL){front=p;rear=p;}else{rear->next=p;rear=p;}}

  • 8/13/2019 Ads a Lab Manual

    18/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 18

    templatevoid queue::del(void){if(front==NULL){

    cout

  • 8/13/2019 Ads a Lab Manual

    19/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 19

    case 4:exit(0);}while(ch!=4)}getch();

    return(0);}

    ####################################################################

    Execution:Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

    Possible Enhancements:As this is created using a linked list the memory can be created dynamically. So,

    there can be no enhancements further.

  • 8/13/2019 Ads a Lab Manual

    20/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 20

    Experiment 3: Deque ADT

    Problem Statement:Write a C++ programs to implement the Deque (double ended queue) ADT using arrays.

    Solution Design:Design a class named Dequeue which has front1, rear1, front2, rear2, size as membervariables. All member variables have to be private. Design 6 public methods, one isDequeue constructor which creates the size of the array dynamically, the othermethods are to insert into the queue from the front and another to insert from therear, the methods to delete the elements from the queue are from the front and fromrear ends and the method display () to print the elements from the queue.

    Class Name:DequeueProperties/Member Variables:int front1, rear1, front2, rear2, size;Constructors:dequeue()

    Public Interface: void insertf (), insertr (), delf (), delr (), display ();Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create a dequeue object which calls the methods of the class.2. Calls the method insertf() to insert the elements from the front end, and the

    method insertr () to insert the elements from the rear end, the methods delf(),delr() to delete the elements the queue from the front and rear ends, and display() method to display the elements in the queue.

    3. If the queue is full, then the element when inserted will not be inserted anddisplays queue overflow and when to remove an element from an empty queueit displays queue underflow, and for displaying in the same condition will showqueue is empty.

    Test Cases:Enter the choice 0. exit 1. insert front 2. insert rear 3. delete front 4. delete rear 5.

    displayTest 1:Input: ch=1Expected Output: enter the element to insert

    Input: n=5Test 2:Input: ch=2Expected Output: enter the element to elementInput: n=3Test 3:Input: ch=5Expected Output: the elements are: 3 5

  • 8/13/2019 Ads a Lab Manual

    21/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 21

    Test 4:Input: ch=4Expected Output: deleted element is 3

    Reference Implementation:####################################################################File: Dequeue.cpp

    #include#includetemplateclass dequeue{int front1,rear1,front2,rear2,size;t *a;public:

    dequeue();void insertf();void insertr();void delf();void delr();void display();

    };templatedequeue::dequeue()

    {front1=rear1=0;

    coutsize;a=new t[size];front2=rear2=size-1;

    for(int i=0;irear2)

    cout

  • 8/13/2019 Ads a Lab Manual

    22/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 22

    templatevoid dequeue::insertr(){if(rear2

  • 8/13/2019 Ads a Lab Manual

    23/90

  • 8/13/2019 Ads a Lab Manual

    24/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 24

    Experiment 4: BinarySearchTree operations

    Problem Statement:

    Write a C++ program to perform the following operations:a) Insert an element into a binary search treeb) Delete an element from a binary search treec) Search for a key element in a binary search tree

    Solution Design:Design a class Node which is used for the linked list declared as friend of class BST,has members data, lchild, rchild. These members are private. Design the actual classBST which has the member variable root of class Node type declared as private. Design6 methods one for inserting the elements into the BST, next to delete an element fromthe BST , another to search an element in the BST, the method to display the elements

    using another method preorder(), the destroy() method to free the nodes created. Allthe methods need to be declared public.

    Class Name: BSTProperties/Member Variables: rootPublic Interface: void destroy (Node *p), insert (const T &e), del (const T&k), display (), preorder (Node *p);bool search (const T &k);Constructors: BST ()Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create the BST object.2. Calls the method insert ()to insert the elements into the BST, the method delete

    () to delete the element from the BST, the method search() to find whether anelement is present in the BST or not, the method display () to print the elementsin the BST.

    3. If the element given for searching is not found, then the method search() displayselement not found.

    Test Cases:Test 1:Enter the choice for 1.insert 2.search 3.delete 4.display 5.exitInput: ch=1Expected Output: enter the element to insertInput: n=5Test 2:Input: ch=1

  • 8/13/2019 Ads a Lab Manual

    25/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 25

    Expected Output: enter the element to insertInput: n=9Test 3:Input: ch=1Expected Output: enter the element to insert

    Input: n=3Test 4:Input: ch=4Expected Output: the elements are: 3 9 5Test 5:Input: ch=3Expected Output: enter the element to be deletedInput: n=5Test 6:Input: ch=2Expected output: enter the element to be searched

    Input: n=9Expected output: element found

    Reference Implementation:#############################################################File: BST.cpp#include#include#includeenum bool{false,true};

    template class Node{friend BST;private:T data;Node *lchild,*rchild;

    };template class BST{

    public: BST(){ root=NULL;}~BST();void destroy(Node *p);bool search(const T &k);void insert(const T &e);void del(const T &k);void display();

  • 8/13/2019 Ads a Lab Manual

    26/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 26

    void preorder(Node *p);private:Node *root;

    };

    templateBST::~BST(){destroy(root);}

    templatevoid BST::destroy(Node *p){if(p){

    destroy(p->lchild);delete p;destroy(p->rchild);}

    }

    templatebool BST::search(const T &k){Node *p=root;while(p)

    {if(kdata)p=p->lchild;else if(k>p->data)p=p->rchild;else return true;

    }return false;}templatevoid BST::insert(const T &e)

    {Node *p=new Node;Node *temp1=root,*temp2;p->data=e;p->lchild=p->rchild=NULL;if(root==NULL)root=p;else

  • 8/13/2019 Ads a Lab Manual

    27/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 27

    {while(temp1){temp2=temp1;if(edata)

    temp1=temp1->lchild;else if(e>temp1->data)temp1=temp1->rchild;else{coutdata)temp2->rchild=p;else temp2->lchild=p;

    }}

    templatevoid BST::del(const T &k){Node *p=root;Node *temp=root,*temp2,*s;while(p){if(kdata)

    {temp=p;p=p->lchild;}else if(k>p->data){temp=p;p=p->rchild;

    }else{

    coutrchild){temp2=s;

  • 8/13/2019 Ads a Lab Manual

    28/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 28

    s=s->rchild;}if(temp2!=p)temp2->rchild=s->lchild;

    else

    temp2->lchild=s->lchild;}else if(p->rchild){s=p->rchild;while(s->lchild){temp2=s;s=s->lchild;}if(temp2!=p)

    temp2->lchild=s->rchild;elsetemp2->rchild=s->rchild;

    }else{s=p;if(p->data>temp->data)temp->lchild=NULL;else temp->lchild=NULL;if(p==root)

    root=NULL;}p->data=s->data;p=NULL;delete s;return;}

    }cout

  • 8/13/2019 Ads a Lab Manual

    29/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 29

    templatevoid BST::preorder(Node *p){if(p)

    {cout

  • 8/13/2019 Ads a Lab Manual

    30/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 30

    }while(t!='n' &&t!='N');}

    ####################################################################Execution:Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

  • 8/13/2019 Ads a Lab Manual

    31/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 31

    Experiment 5: Circular Queue ADT

    Problem Statement:Write a C++ program to implement circular queue ADT using an array.

    Solution Design:Design a class CQ which has a[max], front, rear has its member variables. Themember variables front, rear should be public variables, a[max] a private variable.Design 4 member functions where one is a constructor, the other next one is used toinsert elements into the circular queue, another to delete the elements from thecircular queue, the method display () to print the elements.

    Class Name: CQProperties/Member Variables: a [max], front, rearPublic Interface: void insert (), delete (), display ()Constructors: CQ ()

    Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class that

    does the following.1. Create a CQ object.2. Calls the method insert () to enter the elements into the circular queue, the

    method delete () to delete the elements from the circular queue, and themethod display () to print the elements in the circular queue.

    3. If the elements inserted into the circular queue exceed the max size, then ifdisplays CQ overflow, similarly if the element is to be deleted from the empty

    queue it displays CQ underflow, and in case of displaying the empty it displays CQ empty.

    Test Cases:Enter the choice for 1.insert 2.delete 3.display 4.exitTest 1:Enter the choice for 1.insert 2.delete 3.displayInput: ch=1Expected Output: enter the element to insertInput: n=5Test 2:

    Input: ch=1Expected Output: enter the element to elementInput: n=3Test 3:Input: ch=3Expected Output: the elements are: 3 5Test 4:Input: ch=2

  • 8/13/2019 Ads a Lab Manual

    32/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 32

    Expected Output: deleted element is 3

    Reference Implementation:####################################################################

    File: CQ.cpp#include#include#include#define max 5class CQ{int a[max];public:int front, rear;CQ()

    {rear=front=-1;}void insert(),del(),display();

    };void CQ::insert(){if(((rear==max-1)&&(front==0))||(front==rear+1))cout

  • 8/13/2019 Ads a Lab Manual

    33/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 33

    if(rear==-1)cout

  • 8/13/2019 Ads a Lab Manual

    34/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 34

    case 3:q.display();break;

    case 4:exit(0);}

    } while(ch!=4);

    }

    ####################################################################

    Execution:Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

    Possible Enhancements:The size of the array can be created dynamically without giving it statically.Whenever an overflow condition arises instead of displaying the message we can

    add a method that can create the double size of the array as before to insertthe overflowed element.

  • 8/13/2019 Ads a Lab Manual

    35/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 35

    Experiment 6: Binary Tree Traversal using Non-Recursion

    Problem Statement:Write a c++ programs that use non-recursive functions to traverse the given binary treea) Preorder b) Inorder c) Postorder

    Solution Design:Design a class Binary Search Tree which has struct tree as a node for representingevery element in the tree. This is a private member. Design 6 methods one is aconstructor and other to insert the elements into the tree, and there are 3 methods inwhich the elements can be displayed i.e., the print_preorder (), print_inorder (),print_postorder (). All these are to be declared to be public.Class Name: BinarySearchTreeProperties/Member Variables: struct tree_nodePublic Interface: void print_postorder (), print_inorder (), print_preorder (), insert ().

    Private Methods: void inorder(), preorder(), postorder()

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    Test Cases:Enter your choice: 1. Insertion/Creation 2. In-Order Traversal 3. Pre-Order

    Traversal 4. Post-Order Traversal 5. ExitTest 1:

    Input: ch=1

    Expected Output: Enter the element to be insertedInput: n=5Test 2:Input: ch=1Expected Output: Enter the element to be insertedInput: n=9

    Test 3:Input: ch=1Expected Output: Enter the element to be insertedInput: n=7

    Test 4:

    Input: ch=2Expected Output: Inorder-Traversal : 5 9 7

    Test 5:Input: ch=3Expected Output: Preorder-Traversal : 9 5 7

    Test 6:Input: ch=4Expected Output: Postorder-Traversal : 5 7 9

  • 8/13/2019 Ads a Lab Manual

    36/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 36

    Reference Implementation: Using NonRecursive####################################################################File: BinarySearchTree

    BINARY TRAVERSALS USING NON RECURSIVE/*Binary search tree with all the Recursive and non Recursivetraversals*/

    #include#include#include

    class binarynode{public:int data;binarynode *left;binarynode *right;

    };

    class binsrctree{private:

    binarynode *root;void inorder(binarynode *);void preorder(binarynode *);void postorder(binarynode *);

    public:binsrctree(){root=NULL;

    }void insert(int );void print_inorder();

    void print_preorder();void print_postorder();};

    class stack{int top;binarynode *stackel[20];

  • 8/13/2019 Ads a Lab Manual

    37/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 37

    public:stack(){top=-1;

    }

    void push(binarynode *);binarynode* pop();int empty(){if(top==-1)return(1);

    return(0);}

    };

    void stack::push(binarynode *node){stackel[++top]=node;}

    binarynode *stack::pop(){return(stackel[top--]);}

    class stack_int

    {int top;int stack_int[20];public:stack_int(){top=-1;

    }void push(int flag);int pop();int empty_int()

    {if(top==-1)return(1);

    return(0);}

    };

  • 8/13/2019 Ads a Lab Manual

    38/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 38

    void stack_int::push(int flag){stack_int[++top]=flag;}

    int stack_int::pop(){return(stack_int[top--]);}/*---------------------------------------------------------------------*//* FUNCTION TO INSERT A NODE IN THE TREE *//*---------------------------------------------------------------------*/void binsrctree::insert(int val){binarynode *temp,*prev,*curr;temp=new binarynode;

    temp->data=val;temp->left=temp->right=NULL;

    if(root==NULL){root=temp;

    }else{curr=root;while(curr!=NULL)

    {prev=curr;if(temp->datadata)

    curr=curr->left;else

    curr=curr->right;}if(temp->datadata)

    prev->left=temp;else

    prev->right=temp;

    }}

    /*--------------------------------------------------*//*INORDER NON RECURSIVE TRAVERSAL*//*--------------------------------------------------*/

  • 8/13/2019 Ads a Lab Manual

    39/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 39

    void binsrctree::inorder(binarynode *root){stack stk;binarynode *temp;if(root!=NULL)

    {temp=root;do{while(temp!=NULL){

    stk.push(temp);temp=temp->left;

    }/*end while*/if(!stk.empty()){

    temp=stk.pop();cout

  • 8/13/2019 Ads a Lab Manual

    40/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 40

    {coutleft;}else{if(stk.empty())break;

    temp=stk.pop();flag=stk1.pop();if(flag==2){coutright;

    } /* end else */

  • 8/13/2019 Ads a Lab Manual

    41/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 41

    } /* end if */}while(1);/*end do while*/}/*end function*/

    /*--------------------------------------------------*//*FUNCTION TO PRINT INORDER NON RECURSIVE TRAVERSAL *//*---------------------------------------------------*/

    void binsrctree::print_inorder(){cout

  • 8/13/2019 Ads a Lab Manual

    42/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 42

    binsrctree BST;int ch,element;clrscr();

    do

    {cout

  • 8/13/2019 Ads a Lab Manual

    43/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 43

    Experiment 7: Implementation of BFS and DFS

    Problem Statement:Write a C++ Programs for implementation of BFS AND DFS for a given graph

    Solution Design:Design a main class of the graphs. It contains the 3 methods one to create a graph,and the remaining 2 are for the searches that can be made on the graph i.e., dfs, andbfs. These are declared globally. The struct node, link are the 2 structures that arecreated to specify the link between the nodes.

    Class Name:mainProperties/Member Variables:struct link, node, start, p, q.Constructors:NonePublic Interface:void create (), dfs (), bfs ()Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create a main class which calls the methods create () to form the graph, themethod dfs () to traverse the graph in the depth first search order, and themethod bfs () to traverse the graph in the breadth first search order.

    2. These dfs and bfs methods will display the elements in their respective order.

    Test Cases:Graph: 1-2, 1-4, 2-3, 3-5, 3-6, 4-6, 6-7

    Enter your choice: 1.BFS 2.DFS 3.Exit.Test 1:Input: ch=1Expected Output: Breadth First Search: 1-2-3-4-5-6-7Test 2:Input: ch=2Expected Output: Depth First Search: 1-2-3-5-6-7-4

    Reference Implementation:####################################################################File: Graph.cpp

    #include#include#include

    void create(); // For creating a graphvoid dfs(); // For Deapth First Search(DFS) Traversal.void bfs(); // For Breadth First Search(BFS) Traversal.

  • 8/13/2019 Ads a Lab Manual

    44/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 44

    struct node // Structure for elements in the graph{

    int data,status;struct node *next;

    struct link *adj;};

    struct link // Structure for adjacency list{

    struct node *next;struct link *adj;

    };

    struct node *start, *p, *q;struct link *l, *k;

    int main(){

    int choice;clrscr();create();do{

    cout

  • 8/13/2019 Ads a Lab Manual

    45/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 45

    coutdat;

    if(dat==0)break;p=new node;p->data=dat;p->status=0;p->next=NULL;p->adj=NULL;if(flag==0){

    start=p;q=p;

    flag++;}else{

    q->next=p;q=p;

    }}p=start;while(p!=NULL){

    coutadj=k;l=k;

  • 8/13/2019 Ads a Lab Manual

    46/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 46

    }q=start;while(q!=NULL){

    if(q->data==dat)

    k->next=q;q=q->next;}

    }p=p->next;

    }coutnext;

    }p=start;

    qu[0]=p->data;p->status=1;while(1){

    if(qu[j]==0)break;

    p=start;while(p!=NULL){

    if(p->data==qu[j])break;

    p=p->next;}k=p->adj;while(k!=NULL){

    q=k->next;if(q->status==0){

  • 8/13/2019 Ads a Lab Manual

    47/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 47

    qu[i]=q->data;q->status=1;qu[i+1]=0;i++;

    }

    k=k->adj;}j++;

    }j=0;cout

  • 8/13/2019 Ads a Lab Manual

    48/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 48

    break;p=p->next;

    }coutdata;q->status=1;

    }k=k->adj;

    }}getch();return;

    }

    ####################################################################

    Execution:Step 1: Click Alt+F9 to compile the program.

    Step 2: Click Ctrl+F9 to run the program.

  • 8/13/2019 Ads a Lab Manual

    49/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 49

    Experiment 8:Implementation of sorting methods

    Problem Statement:Write a C++ Programs to implement the following sorting algorithms

    a) Quick Sort

    b) Merge sortc) Heap Sort

    Solution Design:Design a class Sort which has the member variable a. This is a private variable.Design 4 methods one for the creation of the list and the other to display the elementsin the sorted order by using the heap, merge, and quick sorts. This class contains 2constructors one for the default allocation of size to the array of elements to besorted, and the other constructor for dynamic allocation of size for the array.

    Class Name:SortProperties/Member Variables:int a;Constructors:Sort (), Sort (int n)Public Interface:void create (), mergesort (), quicksort (), heapsort (), display ()Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create a Sort object, which can call certain methods.2. Calls the methods create () to insert the elements into the array, the method

    display () to print the elements in the array in the sorted order using themethods heapsort (), quicksort (), mergesort ().

    Test Cases:Test 1:Input: a []= {6,8,3,9,4}Expected Output: using any one of the sorts the sorted order is {3,4,6,8,9}Test 2:Input: a []={15,7,9,34,14}Expected Output: sorted order is: {7,9,14,15,34}

    Reference Implementation:####################################################################File: sort. cpp#include#include#includetemplate

  • 8/13/2019 Ads a Lab Manual

    50/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 50

    class sort{private: int a;public: sort(){int a=new int[50];}

    sort(int n)

    {int a=new int[n];}void create();void heapsort();

    void display();void mergesort();void adjust(int [],int,int);void swap(int a,int b);void print(int [],int);

    void merge(int [],int,int);};

    templatevoid sort::create(){cout

  • 8/13/2019 Ads a Lab Manual

    51/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 51

    j=2*i+1;while((j

  • 8/13/2019 Ads a Lab Manual

    52/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 52

    int mid;if(low

  • 8/13/2019 Ads a Lab Manual

    53/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 53

    case 1: s.heapsort();break;

    case 2:s.mergesort();break;

    case 3:exit(0);

    default: cout

  • 8/13/2019 Ads a Lab Manual

    54/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 54

    Experiment 9: B-Tree Operations

    Problem Statement:Write a C++ Programs to perform the following operations

    a) Insertion into a B-Tree

    b) Deletion from a B-Tree

    Solution Design:Design a class B_Tree which has the nodes as its member variables. All these

    variables are private. Design 6 methods one method to create the B-Tree and onemethod to insert the elements into the tree, one to delete the elements from thetree, another to insert into nonfull tree and to find an element in the tree.

    Class Name:B_TreeProperties/Member Variables: int i, n []

    Constructors:NonePublic Interface: void insert (), insertNonFull (), delete (), create (), search (),splitChild ().Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create a B_Tree object and calls the methods.2. Calls the method create () to create the initially the tree, another method

    insert () the elements into the tree, one method to splitChild when an

    ordering is required, another method search() to find whether an element ispresent in the tree or not, one method to delete the elements from thetree.

    3. If the element to delete is not found in the tree then it displays

    element doesnt exists.

    Test Cases:Enter tour choice: 1. Create 2. Insert 3. Insertnonfull 4. Search 5. SplitChild 6.

    Delete 7. Exit;

    Test 1:

    Input: ch=1Expected Output: enter the element to create:Input: n=8

    Test 2:Input: ch=2Expected Output: enter the element to insert:Input: n=5

    Test 3:

  • 8/13/2019 Ads a Lab Manual

    55/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 55

    Input: ch=2Expected Output: enter the element to insert:Input: n=7

    Test 4:Input: ch=6

    Expected Output: enter the element to delete:Input: n=8

    Reference Implementation:####################################################################File: B-Tree.cpp

    #include

    #include#includeclass B_Tree{

    int i,n[];public:

    void search(int,int);void create(T);void splitChild(int,int,int);void insert(int);void insertNonFull(int);

    void delete(int,int);}

    // B-Tree-Search(x, k)

    void B_Tree::search(int x,int k){

    i

  • 8/13/2019 Ads a Lab Manual

    56/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 56

    // B-Tree-Create(T)

    void B_Tree::create(T){

    x

  • 8/13/2019 Ads a Lab Manual

    57/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 57

    else B-Tree-Insert-Nonfull(r, k)}

    // B-Tree-Insert-Nonfull(x, k)

    void B_Tree::insertNonFull(int x,int k)

    {i = 1 and k < keyi[x]do keyi+1[x]

  • 8/13/2019 Ads a Lab Manual

    58/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 58

    cin>>n;b.create(x,n);break;

    case 2: coutn;

    b.insert(T,n);break;case 3: coutn;b.insertNonFull(x,n);break;

    case 4: coutn;b.search(x,n);

    case 5: b.splitChild(x,i,n);break;

    case 6: coutn;b.delete(x,n);break;

    case 7: exit(0);

    }}while(ch!=7);getch();

    }

    ####################################################################

    Execution:Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

  • 8/13/2019 Ads a Lab Manual

    59/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 59

    Experiment 10: AVL Tree Operations

    Problem Statement:Write a C++ Programs to perform the following operationsa) Insertion into an AVL Treeb) Deletion from an AVL Tree

    Solution Design:Design a class bstree, which has a structure node with members node left, right and

    int height which are declared globally. Also a struct node variable nodeptr declared asglobal. Design methods where one is to insert the elements into the AVL tree, and tofind an element in the element, and to display the min and max elements in the tree

    and to display in the in, pre, and postorder traversals, and methods to delete the minand max values.

    Class Name:BstreeProperties/Member Variables: struct node, nodeptrConstructors:NonePublic Interface:void insert (), deletemin (), deletemax (), inorder (), postorder (),preorder (), find (), findmin (),findmax ().Private Methods:None

    Unit Testing Code:

    Write a main method in the same class above or preferably in a different class thatdoes the following.1. Create a bstree object and call the methods.2. Calls the method insert () to insert the element in the AVL tree, and 2

    methods findmin (), findmax () to find min and max elements in the tree, and find()method to find an element in the tree, copy () method to copy the AVL tree toprint in the inorder format, the method delete() to remove the elements from theAVL tree, and the tree traversals are used to display the elements, and height ()method to find the levels of the AVL tree.

    Test Cases:Enter your choice: 1.Insertion 2.FindMin 3.FindMax 4.Find 5.Copy 6.Delete

    7.Preorder 8.Inorder 9.Postorder 10.heightTest 1:

    Input: ch=1Expected Output: enter the element to be inserted:Input: n=7

    Test 2:

  • 8/13/2019 Ads a Lab Manual

    60/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 60

    Input: ch=1Expected Output: enter the element to be inserted:Input: n=4

    Test 3:Input: ch=1

    Expected Output: enter the element to be inserted:Input: n=6Test 4:

    Input: ch=1Expected Output: enter the element to be inserted:Input: n=2

    Test 5:Input: ch=2Expected Output: the minimum element is: 2

    Test 6:Input: ch=3

    Expected Output: the maximum element is: 7Test 7:Input: ch=6Expected Output: enter the element to be deleted : 2

    Test 8:Input: ch=8Expected Output: the inorder traversal is : 4 6 7

    Reference Implementation:

    ####################################################################File: AVLTrees.cpp/* Adelson Velseky Landis Tree */

    # include # include # include

    struct node{

    int element;

    node *left;node *right;int height;

    };

    typedef struct node *nodeptr;

    class bstree

  • 8/13/2019 Ads a Lab Manual

    61/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 61

    {

    public:void insert(int,nodeptr &);void del(int, nodeptr &);

    int deletemin(nodeptr &);void find(int,nodeptr &);nodeptr findmin(nodeptr);nodeptr findmax(nodeptr);void copy(nodeptr &,nodeptr &);void makeempty(nodeptr &);nodeptr nodecopy(nodeptr &);void preorder(nodeptr);void inorder(nodeptr);void postorder(nodeptr);int bsheight(nodeptr);

    nodeptr srl(nodeptr &);nodeptr drl(nodeptr &);nodeptr srr(nodeptr &);nodeptr drr(nodeptr &);int max(int,int);int nonodes(nodeptr);

    };

    // Inserting a nodevoid bstree::insert(int x,nodeptr &p){

    if (p == NULL){p = new node;p->element = x;p->left=NULL;p->right = NULL;p->height=0;if (p==NULL)

    coutleft) - bsheight(p->right))==2){

    if (x < p->left->element)p=srl(p);

  • 8/13/2019 Ads a Lab Manual

    62/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 62

    elsep = drl(p);

    }}else if (x>p->element)

    { insert(x,p->right);if ((bsheight(p->right) - bsheight(p->left))==2){

    if (x > p->right->element)p=srr(p);

    elsep = drr(p);

    }}else

    coutright);d=max(m,n);p->height = d + 1;

    }

    // Finding the Smallest

    nodeptr bstree::findmin(nodeptr p){if (p==NULL){

    coutleft;

    return p;}

    }

    // Finding the Largestnodeptr bstree::findmax(nodeptr p){

    if (p==NULL)

  • 8/13/2019 Ads a Lab Manual

    63/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 63

    {coutright;

    return p;}

    }

    // Finding an elementvoid bstree::find(int x,nodeptr &p){

    if (p==NULL)

    coutleft);elseif (x>p->element)

    find(x,p->right);else

    coutright);d=p;free(d);p=NULL;

  • 8/13/2019 Ads a Lab Manual

    64/90

  • 8/13/2019 Ads a Lab Manual

    65/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 65

    p=p->left;free(d);coutright);}

    int bstree::deletemin(nodeptr &p){

    int c;coutelement;p=p->right;

    return c;}else{c=deletemin(p->left);return c;

    }}

    void bstree::preorder(nodeptr p){

    if (p!=NULL){coutright);

    }}

    // Inorder Printingvoid bstree::inorder(nodeptr p){

    if (p!=NULL){

    inorder(p->left);cout

  • 8/13/2019 Ads a Lab Manual

    66/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 66

    // PostOrder Printingvoid bstree::postorder(nodeptr p){

    if (p!=NULL){

    postorder(p->left);postorder(p->right);coutheight;return t;

    }}

    nodeptr bstree:: srl(nodeptr &p1){

    nodeptr p2;p2 = p1->left;p1->left = p2->right;p2->right = p1;p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;p2->height = max(bsheight(p2->left),p1->height) + 1;return p2;

    }

    nodeptr bstree:: srr(nodeptr &p1){

    nodeptr p2;p2 = p1->right;p1->right = p2->left;p2->left = p1;p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1;

  • 8/13/2019 Ads a Lab Manual

    67/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 67

    p2->height = max(p1->height,bsheight(p2->right)) + 1;return p2;

    }

    nodeptr bstree:: drl(nodeptr &p1){p1->left=srr(p1->left);return srl(p1);

    }

    nodeptr bstree::drr(nodeptr &p1){

    p1->right = srl(p1->right);return srr(p1);

    }

    int bstree::nonodes(nodeptr p){

    int count=0;if (p!=NULL){

    nonodes(p->left);nonodes(p->right);count++;

    }return count;

    }

    int main(){

    clrscr();nodeptr root,root1,min,max;//,flag;int a,choice,findele,delele,leftele,rightele,flag;char ch='y';

    bstree bst;//system("clear");root = NULL;root1=NULL;cout

  • 8/13/2019 Ads a Lab Manual

    68/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 68

    cout

  • 8/13/2019 Ads a Lab Manual

    69/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 69

    bst.postorder(root);break;

    case 10: cout

  • 8/13/2019 Ads a Lab Manual

    70/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 70

    Experiment 11: Implementation of Kruskals Algorithm

    Problem Statement:Write a C++ Programs to implement Kruskals algorithm to generate a minimumspanning tree

    Solution Design:Design a class Kruskal which has the members like weight, vertex, edge which are

    private variables. Design 2 methods one to create the graph, another method todevelop the less cost for visiting the entire graph.

    Class Name:Kruskal

    Properties/Member Variables:vertex, edge, weightConstructors:NonePublic Interface:void create (), mincost ().Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create an object which calls the methods.2. Calls the method create () to create the graph and the method mincost () to

    find the minimum cost for visiting the entire graph.

    Test Cases:Creating the graph with their respective weights:1-(4)-4, 1-(2)-5, 4-(6)-6, 4-(1)-7, 5-(3)-6, 6-(4)-2, 2-(2)-3

    Test:Input: MincostExpected Output: the min_cost of the graph using Kruskals algorithm is: 17

    Reference Implementation:####################################################################File: Kruskal.cpp

    Graph& KruskalsAlgorithm (Graph const& g){

    unsigned int const n = g.NumberOfVertices ();

    Graph& result = *new GraphAsLists (n);for (Vertex::Number v = 0; v < n; ++v)

    result.AddVertex (*new Vertex (v));

  • 8/13/2019 Ads a Lab Manual

    71/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 71

    PriorityQueue& queue = *new BinaryHeap (g.NumberOfEdges ());Iterator& p = g.Edges ();while (!p.IsDone ()) {

    WeightedEdge& edge =

    dynamic_cast (*p);Int& weight = dynamic_cast (edge.Weight ());queue.Enqueue (*new Assoc (weight, edge));++p;

    }delete &p;

    Partition& partition = *new PartitionAsForest (n);while (!queue.IsEmpty () && partition.Count () > 1){

    Assoc& assoc =

    dynamic_cast (queue.DequeueMin ());Edge& edge = dynamic_cast (assoc.Value ());Vertex::Number const v0 = edge.V0 ();Vertex::Number const v1 = edge.V1 ();Set& s = partition.Find (Set::Element (v0));Set& t = partition.Find (Set::Element (v1));if (s != t){

    partition.Join (s, t);result.AddEdge (*new Edge (result[v0], result[v1]));

    }

    delete &assoc;}delete &partition;delete &queue;return result;

    }

    ####################################################################

    Execution:

    Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

  • 8/13/2019 Ads a Lab Manual

    72/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 72

    Experiment 12: Implementation of Prims Algorithm

    Problem Statement:Write a C++ Programs to implement Prims algorithm to generate a minimum spanningtree

    Solution Design:Design a class Prims which has the members like weight, vertex, edge which are

    private variables. Design 2 methods one to create the graph, another method todevelop the less cost for visiting the entire graph.

    Class Name:PrimsProperties/Member Variables:vertex, edge, weightConstructors:NonePublic Interface:void create (), mincost ().Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create an object which calls the methods.2. Calls the method create () to create the graph and the method mincost () to

    find the minimum cost for visiting the entire graph.

    Test Cases:Creating the graph with their respective weights:1-(4)-4, 1-(2)-5, 4-(6)-6, 4-(1)-7, 5-(3)-6, 6-(4)-2, 2-(2)-3

    Test:Input: MincostExpected Output: the min_cost of the graph using Prims algorithm is: 17

    Reference Implementation:

    ####################################################################File: Prims.cppGraph& PrimsAlgorithm (Graph const& g, Vertex const& s){

    unsigned int const n = g.NumberOfVertices ();Array table (n);PriorityQueue& queue = *new BinaryHeap (g.NumberOfEdges ());table [s].distance = 0;

  • 8/13/2019 Ads a Lab Manual

    73/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 73

    queue.Enqueue (*new Assoc (0, const_cast (s)));while (!queue.IsEmpty ()){

    Assoc& assoc =dynamic_cast (queue.DequeueMin ());

    Vertex& v0 = dynamic_cast (assoc.Value ());if (!table [v0].known){

    table [v0].known = true;Iterator& p = g.EmanatingEdges (v0);while (!p.IsDone ()) {

    WeightedEdge& edge =dynamic_cast (*p);

    Vertex& v1 = edge.Mate (v0);Int& weight =

    dynamic_cast (edge.Weight ());

    int const d = weight;if (!table[v1].known && table[v1].distance > d){

    table [v1].distance = d;table [v1].predecessor = v0;queue.Enqueue (*new Assoc (d, v1));

    }++p;

    }delete &p;

    }

    delete &assoc;}delete &queue;

    Graph& result = *new GraphAsLists (n);for (Vertex::Number v = 0; v < n; ++v)

    result.AddVertex (*new Vertex (v));

    for (Vertex::Number v = 0; v < n; ++v)if (v != s)

    result.AddEdge (*new Edge (

    result [v], result [table [v].predecessor]));return result;

    }

    ####################################################################

    Execution:

  • 8/13/2019 Ads a Lab Manual

    74/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 74

    Step 1: Click Alt+F9 to compile the program.Step 2: Click Ctrl+F9 to run the program.

  • 8/13/2019 Ads a Lab Manual

    75/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 75

    Experiment 13: Implementation of Hashing functions

    Problem Statement:Write a C++ Programs to implement all the functions of a dictionary (ADT) usinghashing.

    Solution Design:Design a class Hashtable which has list array which is a private variable.

    Design 5 methods one is constructor, another is to insert the values into the table,another is to delete the elements from the table, one is to view the element in thehashtable, one is to find an element in the table.

    Class Name:HashtableProperties/Member Variables: list table [];Constructors: Hashtable ()

    Public Interface:void view (), bool insert (), remove (), type find ()Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    1. Create a hashtable object which calls the methods.

    2. Calls the method insert () which inserts the elements into the table, the methodremove () to remove the elements from the table, one method find () is toknown whether an element is in the table or not, another method view () is toview the hash table.

    3. If the element to search is not found in the table it will display element notfound.

    Test Cases:Enter your choice: 1. Insert 2. Delete 3. Search 4. View 5. Exit

    Test 1:Input: ch=1Expected Output: enter the element to insert:Input: n=5

    Test 2:Input: ch=1

    Expected Output: enter the element to insert:Input: n=6

    Test 3:Input: ch=1Expected Output: enter the element to insert:Input: n=2

    Test 4:Input: ch=4

  • 8/13/2019 Ads a Lab Manual

    76/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 76

    Expected Output: elements in the HashTable are: 5 6 2Test 5:

    Input: ch=2Expected Output: enter the element to be deleted:Input: n=6

    Test 6:Input: ch=2Expected Output: enter the element to find:Input: n=2Expected Output: element found

    Reference Implementation:####################################################################File: Hashing.cpp

    #include#include#include#ifndef _HASHTABLE_H#define _HASHTABLE_H

    #include "type.h"#include "list.h"#include "listiter.h"#include

    #define TABLE_SIZE 33

    class Hashtable{

    public:Hashtable();bool insert (Type *);void view();Type* find (char*);bool remove(char *);

    private:List* table[TABLE_SIZE];int hash (char*); //hash function

    };

    #endif //_HASHTABLE_H

  • 8/13/2019 Ads a Lab Manual

    77/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 77

    #include "hashtable.h"#define DEBUG 1

    Hashtable::Hashtable()

    { for(int i = 0; i < TABLE_SIZE; i++)table[i] = 0;

    }

    //Hash Function: sum of the ASCII codes of the characters % TABLE_SIZEint Hashtable::hash (char *l){

    int long sum = 0;

    int len = strlen(l);

    for(int i = 0; i < len; i++)sum += l[i];

    return sum % TABLE_SIZE;

    }

    bool Hashtable::insert (Type* new_item){

    int index;

    List* list;Node* p;

    index = hash(new_item->get_key());

    if(DEBUG)cout

  • 8/13/2019 Ads a Lab Manual

    78/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 78

    return true;}

    return false; //should never get here

    }

    void Hashtable::view(){

    for(int i = 0; i < TABLE_SIZE; i++) {if(table[i] != 0 ){

    List list = *table[i];ListIter iter(list);

    while(!iter.done()) {

    if(strcmp(iter.value().get_key(), "*") != 0)cout

  • 8/13/2019 Ads a Lab Manual

    79/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 79

    *item = p->getinfo();return item;

    }}

    bool Hashtable::remove(char *key){int index, new_index;List list;

    new_index = index = hash(key);

    if (table[index] == 0)return false;

    list = *table[index];

    ListIter iter(list);

    while(!iter.done()) {

    Node *node = iter.lookup();

    Type value = node->getinfo();

    if (strcmp(value.get_key(), key) == 0) {value.set_key("*");

    node->setinfo(value);return true;}

    iter.next();}

    return false;}

    void main()

    {Hashtable *table;table = new Hashtable();int flag = 1;

    while(flag){

    int choice;

  • 8/13/2019 Ads a Lab Manual

    80/90

  • 8/13/2019 Ads a Lab Manual

    81/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 81

    cout key;cin.get ();

    result = table->remove(key);

    if(result == true)cout

  • 8/13/2019 Ads a Lab Manual

    82/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 82

    ADDITIONAL PROGRAMS

  • 8/13/2019 Ads a Lab Manual

    83/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 83

    Experiment 14: Binary Tree Traversal using Recursion

    Problem Statement:

    Write a c++ programs that use recursive functions to traverse the given binary treea) Preorder b) Inorder c) Postorder

    Solution Design:Design a class Binary Search Tree which has struct tree as a node for representingevery element in the tree. This is a private member. Design 6 methods one is aconstructor and other to insert the elements into the tree, the other to delete fromthe tree, and there are 3 methods in which the elements can be displayed i.e., thepreorder (), inorder (), postorder (). All these are to be declared to be public.

    Class Name: BinarySearchTreeProperties/Member Variables: struct tree_nodePublic Interface: void print_postorder (), print_inorder (), print_preorder (), insert (),remove ().Private Methods:None

    Unit Testing Code:Write a main method in the same class above or preferably in a different class thatdoes the following.

    Test Cases:

    Enter your choice: 1. Insertion/Creation 2. In-Order Traversal 3. Pre-OrderTraversal 4. Post-Order Traversal 5. Removal 6. ExitTest 1:

    Input: ch=1Expected Output: Enter the element to be insertedInput: n=5

    Test 2:Input: ch=1Expected Output: Enter the element to be insertedInput: n=9

    Test 3:

    Input: ch=1Expected Output: Enter the element to be insertedInput: n=7

    Test 4:Input: ch=2Expected Output: Inorder-Traversal : 5 9 7

    Test 5:Input: ch=3

  • 8/13/2019 Ads a Lab Manual

    84/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 84

    Expected Output: Preorder-Traversal : 9 5 7Test 6:Input: ch=4Expected Output: Postorder-Traversal : 5 7 9

    Reference Implementation: Using Recursive####################################################################File: BinarySearchTree#include #include using namespace std;

    class BinarySearchTree{

    private:

    struct tree_node{tree_node* left;tree_node* right;ints data;

    };tree_node* root;

    public:BinarySearchTree(){

    root = NULL;

    }bool isEmpty() const { return root==NULL; }void print_inorder();void inorder(tree_node*);void print_preorder();void preorder(tree_node*);void print_postorder();void postorder(tree_node*);void insert(int);void remove(int);

    };

    // Smaller elements go left// larger elements go rightvoid BinarySearchTree::insert(int d){

    tree_node* t = new tree_node;tree_node* parent;t->data = d;

  • 8/13/2019 Ads a Lab Manual

    85/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 85

    t->left = NULL;t->right = NULL;parent = NULL;

    // is this a new tree?if(isEmpty()) root = t;

    else{//Note: ALL insertions are as leaf nodestree_node* curr;curr = root;// Find the Node's parentwhile(curr){

    parent = curr;if(t->data > curr->data) curr = curr->right;else curr = curr->left;

    }

    if(t->data < parent->data)parent->left = t;

    elseparent->right = t;

    }}

    void BinarySearchTree::remove(int d){

    //Locate the elementbool found = false;if(isEmpty()){

    cout

  • 8/13/2019 Ads a Lab Manual

    86/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 86

    parent = curr;if(d>curr->data) curr = curr->right;else curr = curr->left;

    }}

    if(!found) {cout

  • 8/13/2019 Ads a Lab Manual

    87/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 87

    }return;}

    //We're looking at a leaf node

    if( curr->left == NULL && curr->right == NULL){if(parent->left == curr) parent->left = NULL;else parent->right = NULL;

    delete curr;return;

    }

    //Node with 2 children// replace node with smallest value in right subtree

    if (curr->left != NULL && curr->right != NULL){tree_node* chkr;chkr = curr->right;if((chkr->left == NULL) && (chkr->right == NULL)){

    curr = chkr;delete chkr;curr->right = NULL;

    }else // right child has children

    { //if the node's right child has a left child// Move all the way down left to locate smallest element

    if((curr->right)->left != NULL){

    tree_node* lcurr;tree_node* lcurrp;lcurrp = curr->right;lcurr = (curr->right)->left;while(lcurr->left != NULL)

    {lcurrp = lcurr;lcurr = lcurr->left;

    }curr->data = lcurr->data;

    delete lcurr;lcurrp->left = NULL;

    }

  • 8/13/2019 Ads a Lab Manual

    88/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 88

    else{

    tree_node* tmp;tmp = curr->right;curr->data = tmp->data;

    curr->right = tmp->right;delete tmp;}

    }return;

    }

    }

    void BinarySearchTree::print_inorder()

    { inorder(root);}

    void BinarySearchTree::inorder(tree_node* p){

    if(p != NULL){

    if(p->left) inorder(p->left);cout

  • 8/13/2019 Ads a Lab Manual

    89/90

    Department of IT ADSA Lab Manual

    SVCET, CTR 89

    void BinarySearchTree::print_postorder(){postorder(root);

    }

    void BinarySearchTree::postorder(tree_node* p){

    if(p != NULL){

    if(p->left) postorder(p->left);if(p->right) postorder(p->right);cout

  • 8/13/2019 Ads a Lab Manual

    90/90

    Department of IT ADSA Lab Manual

    cout