Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

EX NO:1 IMPLEMENTATION OF RECURSIVE FUNCTION FOR

TREE DATE: TRAVERSAL AND


FIBONACCI

AIM:
To write a c++ program to implement the recursive function for tree
traversal and Fibonacci.

ALGORITHM:
1. Start.
2. Get the number nto which Factorial value is to be calculated.
3. Print Menu
4. If choice=1 then Call Factorial(n).
5. Else if choice=2 then Call NonRecFactorial(n)
6. Cout factorial Number
7. Stop

PROGRAM1:
#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}}
struct node* insertNode(struct node* node, int val) {
if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);
insertNode(root, 3);
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root);
return 0;
}

OUTPUT:
In-Order traversal of the Binary Search Tree is: 1 2 3 4 5
PROGRAM 2:
#include <iostream>
using namespace std;
int fib(int x) {
if((x==1)||(x==0)) {
return(x);
}else {
return(fib(x-1)+fib(x-2)); }}
int main() {
int x , i=0;
cout << "Enter the number of terms of series : ";
cin >> x;
cout << "\nFibonnaci Series : ";
while(i < x) {
cout << " " << fib(i);
i++; }
return 0;}
OUTPUT:
Enter the number of terms of series : 15
Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

RESULT:
EX NO:2 IMPLEMENTATION OF ITERATION FUNCTION
DATE: TRAVERSAL AND FIBONNACI

AIM:
To write a c++ program to implement the iteration for tree traversal and
Fibonacci.

ALGORITHM:

1. Start.
2. Get the number into which Factorial value is to be calculated.
3. Print Menu 1. Recursive function
4. If choice=1 then Call Factorial(n).
5. Else if choice=2 then Call NonRecFactorial(n)
6. Cout factorial Number
7. Stop

PROGRAM1:

#include <iostream>
#include <stack>
using namespace std;
struct Node
{ int data;
Node *left, *right;
Node(int data)
{
this->data = data;
this->left = this->right = nullptr;}};
void inorderIterative(Node* root)
{ stack<Node*> stack;
Node* curr = root;
while (!stack.empty() || curr != nullptr)
{
if (curr != nullptr){
stack.push(curr);
curr = curr->left;}
else {
curr = stack.top();
stack.pop();
cout << curr->data << " ";
curr = curr->right;}}}
int main()
{
/* Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/\
/ \
7 8
*/

Node* root = new Node(1);


root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->left = new Node(7);
root->right->left->right = new Node(8);
inorderIterative(root);
return 0;
}

OUTPUT:

42175836
PROGRAM2:
#include <iostream>
using namespace std;
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;}}
int main() {
int num;
cout << "Enter the number : ";
cin >> num;
cout << "\nThe fibonacci series : " ;
fib(num);
return 0;
}
OUTPUT:
Enter the number : 10
The fibonacci series : 0 1 1 2 3 5 8 13 21 34

RESULT:
EX NO:3 IMPLEMENTATION OF MERGE SORT AND
DATE: QUICK SORT

AIM:
To write a c++ program to implement merge sort and quick sort.

ALGORITHM:

1.Take input of data.


2. Call MergeSort() function.
3. Recursively split the array into two equal parts.
4. Split them until we get at most one element in both half.
5. Combine the result by invoking Merge().
6. It combines the individually sorted data from low to mid and mid+1 to high.
7. Return to main and display the result.
8. Exit.

PROGRAM:
#include <iostream>
using namespace std;
void Merge(int *a, int low, int high, int mid)
{
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;

while (i <= mid && j <= high)


{
if (a[i] < a[j]){
temp[k] = a[i];
k++;
i++;}else{
temp[k] = a[j];
k++;
j++;}}
while (i <= mid){
temp[k] = a[i];
k++;
i++;}while (j <= high)
{temp[k] = a[j];
k++;
j++;}
for (i = low; i <= high; i++)
{a[i] = temp[i-low];}}
void MergeSort(int *a, int low, int high)
{int mid;
if (low < high)
{
mid=(low+high)/2;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
Merge(a, low, high, mid);}}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
MergeSort(arr, 0, n-1);
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;}

OUTPUT:

Case 1:
Enter the number of data element to be sorted: 10
Enter element 1: 23
Enter element 2: 987
Enter element 3: 45
Enter element 4: 65
Enter element 5: 32
Enter element 6: 9
Enter element 7: 475
Enter element 8: 1
Enter element 9: 17
Enter element 10: 3

Sorted Data ->1->3->9->17->23->32->45->65->475->987


PROGRAM2:
#include <iostream>
using namespace std;
void quick_sort(int[],int,int);
int partition(int[],int,int);
int main()
{
int a[50],n,i;
cout<<"How many elements?";
cin>>n;
cout<<"\nEnter array elements:";
for(i=0;i<n;i++)
cin>>a[i];
quick_sort(a,0,n-1);
cout<<"\nArray after sorting:";
for(i=0;i<n;i++)
cout<<a[i]<<" "; return 0; }
void quick_sort(int a[],int l,int u)
{
int j;
if(l<u) {
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u); } }
int partition(int a[],int l,int u)
{ int v,i,j,temp;
v=a[l];
i=l;
j=u+1;
do{
do
i++;
while(a[i]<v&&i<=u);
do
j--;
while(v<a[j])
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
OUTPUT:

How many elements:6


Enter array elements:9 15 6 7 10 12
Array after sorting:6 7 9 10 12 15

RESULT:
EX NO:4 IMPLEMENTATION OF A BINARY SEARCH TREE
DATE:

AIM:
To implement a binary search tree.
ALGORITHM:

 1.Start the program.Create the following program to search binary tree


 Create() an empty tree.
 2.Insert()insert a node in the tree.
 3.Search() to searches for a node in the tree.
 4.Delete() deletes a node from the tree.
 5.Inorder() in-order traversal of the tree.
 6.Preorder()pre-order traversal of the tree.
 7.Postorder() post-order traversal of the tree.
 8.stop the program

PROGRAM:
# include <iostream>
# include <cstdlib>
using namespace std;
struct nod//node declaration
{
int info;
struct nod *l;
struct nod *r;
}*r;
class BST
{
public://functions declaration
void search(nod *, int);
void find(int, nod **, nod **);
void insert(nod *, nod *);
void del(int);
void casea(nod *,nod *);
void caseb(nod *,nod *);
void casec(nod *,nod *);
void preorder(nod *);
void inorder(nod *);
void postorder(nod *);
void show(nod *, int);
BST(){ r = NULL; }};
void BST::find(int i, nod **par, nod **loc)//find the position of the item
{nod *ptr, *ptrsave;
if (r == NULL){
*loc = NULL;
*par = NULL;
return;} if (i == r→info)
{ *loc = r;
*par = NULL;
return;}
if (i < r→info)
ptr = r→l;
else
ptr = r→r;
ptrsave = r;
while (ptr != NULL)
{ if (i == ptr→info) {
*loc = ptr;
*par = ptrsave;
return; }
ptrsave = ptr;
if (i < ptr→info)
ptr = ptr→l;
else
ptr = ptr→r; }
*loc = NULL;
*par = ptrsave;}
void BST::search(nod *root, int data) //searching
par→l = NULL;
else
par→r = NULL; }}
void BST::caseb(nod *par, nod *loc){
nod *child;
if (loc→l!= NULL)
child = loc→l;
else
child = loc→r;
if (par == NULL) {
r = child; }
else {
if (loc == par→l)
par→l = child; else
par→r = child; }}
void BST::casec(nod *par, nod *loc)
{
nod *ptr, *ptrsave, *suc, *parsuc;
ptrsave = loc;
ptr = loc→r;
while (ptr→l!= NULL) {
ptrsave = ptr;
ptr = ptr→l; }
suc = ptr;
parsuc = ptrsave;
if (suc→l == NULL && suc→r == NULL)
casea(parsuc, suc);
else
caseb(parsuc, suc);
if (par == NULL) { r = suc; }
else
{
if (loc == par→l)
par→l = suc;
else par→r= suc; }
suc→l = loc→l;
suc→r= loc→r;}
void BST::preorder(nod *ptr)
{ if (r == NULL)
{ cout<<"Tree is empty"<<endl; return; }
if (ptr != NULL)
{
cout<<ptr→info<<" ";
preorder(ptr→l);
preorder(ptr→r);
}}
void BST::inorder(nod *ptr)//inorder traversal
{if (r == NULL)
{ cout<<"Tree is empty"<<endl;
Return; }
if (ptr != NULL)
{
inorder(ptr→l);
cout<<ptr→info<<" ";
inorder(ptr→r); }}
void BST::postorder(nod *ptr)//postorder traversal
{ if (r == NULL)
{ cout<<"Tree is empty"<<endl;
return; }
if (ptr != NULL) {
postorder(ptr→l);
postorder(ptr→r);
cout<<ptr→info<<" ";}}
void BST::show(nod *ptr, int level)//print the tree
{
int i;
if (ptr != NULL)
{
show(ptr→r, level+1);
cout<<endl;
if (ptr == r)
cout<<"Root→: ";
else {
for (i = 0;i < level;i++)
cout<<" "; }
cout<<ptr→info;
show(ptr→l, level+1); }}
int main()
{ int c, n,item;
BST bst;
nod *t;
while (1) {
cout<<"1.Insert Element "<<endl;
cout<<"2.Delete Element "<<endl;
cout<<"3.Search Element"<<endl;
cout<<"4.Inorder Traversal"<<endl;
cout<<"5.Preorder Traversal"<<endl;
cout<<"6.Postorder Traversal"<<endl;
cout<<"7.Display the tree"<<endl;
cout<<"8.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>c;
switch(c) {
case 1:
t = new nod;
cout<<"Enter the number to be inserted : ";
cin>>t→info;
bst.insert(r, t);
break;
case 2:
if (r == NULL { cout<<"Tree is empty, nothing to delete"<<endl;
continue }
cout<<"Enter the number to be deleted : ";
cin>>n;
bst.del(n);
break;
case 3:
cout<<"Search:"<<endl;
cin>>item;
bst.search(r,item);
break;
case 4:
cout<<"Inorder Traversal of BST:"<<endl;
bst.inorder(r);
cout<<endl;
break;
case 5:
cout<<"Preorder Traversal of BST:"<<endl;
bst.preorder(r);
cout<<endl;
break;
case 6:
cout<<"Postorder Traversal of BST:"<<endl;
bst.postorder(r);
cout<<endl; break;
case 7:
cout<<"Display BST:"<<endl;
bst.show(r,1);
cout<<endl; break;
case 8; exit(1);
default:
cout<<"Wrong choice"<<endl>> } }}
OUTPUT:
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 1
Enter the number to be inserted : 6
Root Node is Added
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 1
Enter the number to be inserted : 7
Node Added To Right
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 2
Enter the number to be deleted : 5
item deleted
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 7
Display BST:
7
Root→: 6
4
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 8

RESULT:
EXNO:5 RED - BLACK TREE IMPLEMENTATION
DATE:

AIM:
To implement red-black tree.

ALGORITHM:

1.start the program.


2.Declare the variables.
3.Every node is either red or black.
4.Every leaf (NULL) is black.
5.If a node is red, then both its children are black.
6.Every simple path from a node to a descendant leaf contains red tree.
7.stop the program.

PROGRAM:

#include<iostream>
using namespace std;
struct node
{
int key;
node *parent;
char color;
node *left;
node *right;
};
class RBtree
{
node *root;
node *q;
public :
RBtree()
{
q=NULL;
root=NULL;
}
void insert();
void insertfix(node *);
void leftrotate(node *);
void rightrotate(node *);
void del();
node* successor(node *);
void delfix(node *);
void disp();
void display( node *);
void search();
};
void RBtree::insert()
{
int z,i=0;
cout<<"\nEnter key of the node to be inserted: ";
cin>>z;
node *p,*q;
node *t=new node;
t->key=z;
t->left=NULL;
t->right=NULL;
t->color='r';
p=root;
q=NULL;
if(root==NULL)
{
root=t;
t->parent=NULL;} else
{
while(p!=NULL) {
q=p;
if(p->key<t->key)
p=p->right;
else
p=p->left; }
t->parent=q;
if(q->key<t->key)
q->right=t;
else
q->left=t; }
insertfix(t);}
void RBtree::insertfix(node *t)
{
node *u;
if(root==t) {
t->color='b';
return; }
while(t->parent!=NULL&&t->parent->color=='r')
{ node *g=t->parent->parent;
if(g->left==t->parent) {
if(g->right!=NULL)
{
u=g->right;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g; }}
else
{
if(t->parent->right==t)
{
t=t->parent;
leftrotate(t); }
t->parent->color='b';
g->color='r';
rightrotate(g); } }
else
{ if(g->left!=NULL)
{
u=g->left;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g; }}
else
{
if(t->parent->left==t)
{
t=t->parent;
rightrotate(t);
}
t->parent->color='b';
g->color='r';
leftrotate(g); } }
root->color='b'; }}

void RBtree::del()
{
if(root==NULL)
{
cout<<"\nEmpty Tree." ;
return ;
}
int x;
cout<<"\nEnter the key of the node to be deleted: ";
cin>>x;
node *p;
p=root;
node *y=NULL;
node *q=NULL;
int found=0;
while(p!=NULL&&found==0)
{
if(found==0)
cout<<"\nElement Not Found.";
else
{
cout<<"\n\t FOUND NODE: ";
cout<<"\n Key: "<<p->key;
cout<<"\n Colour: ";
if(p->color=='b')
cout<<"Black";
else
cout<<"Red";
if(p->parent!=NULL)
cout<<"\n Parent: "<<p->parent->key;
else
cout<<"\n There is no parent of the node. ";
if(p->right!=NULL)
cout<<"\n Right Child: "<<p->right->key;
else
cout<<"\n There is no right child of the node. ";
if(p->left!=NULL)
cout<<"\n Left Child: "<<p->left->key;
else
cout<<"\n There is no left child of the node. ";
cout<<endl;

}
}
int main()
{
int ch,y=0;
RBtree obj;
do
{
cout<<"\n\t RED BLACK TREE " ;
cout<<"\n 1. Insert in the tree ";
cout<<"\n 2. Delete a node from the tree";
cout<<"\n 3. Search for an element in the tree";
cout<<"\n 4. Display the tree ";
cout<<"\n 5. Exit " ;
cout<<"\nEnter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1 : obj.insert();
cout<<"\nNode Inserted.\n";
break;
case 2 : obj.del();
break;
case 3 : obj.search();
break;
case 4 : obj.disp();
break;
case 5 : y=1;
break;
default : cout<<"\nEnter a Valid Choice.";
}
cout<<endl;

}while(y!=1);
return 1;
}

OUTPUT:
RESULT:
EX NO:6 HEAP IMPLEMENTATION
DATE:

AIM:
To write a program to implement heap.

ALGORITHM:

1.Start the program.


2.The heap itself has, by definition, the largest value at the top of the tree, so the
heap sort algorithm must also reverse the order.
3.It does this with the following steps:
4.Remove the topmost item (the largest) and replace it with the rightmost leaf.
The topmost item is stored in an array.
5.Re-establish the heap.
6.Repeat steps 1 and 2 until there are no more items left in the heap.
7.The sorted elements are now stored in an array

PROGRAM:

#include <iostream>
using namespace std;
void MAX_HEAPIFY(int a[], int i, int n)
{
int l,r,largest,loc;
l=2*i;
r=(2*i+1);
if((l<=n)&&a[l]>a[i])
largest=l;
else
largest=i;
if((r<=n)&&(a[r]>a[largest]))
largest=r;
if(largest!=i)
{
loc=a[i];
a[i]=a[largest];
a[largest]=loc;
MAX_HEAPIFY(a, largest,n);
}
}
void BUILD_MAX_HEAP(int a[], int n)
{
for(int k = n/2; k >= 1; k--)
{
MAX_HEAPIFY(a, k, n);
}
}
void HEAPSORT(int a[], int n)
{

BUILD_MAX_HEAP(a,n);
int i, temp;
for (i = n; i >= 2; i--)
{
temp = a[i];
a[i] = a[1];
a[1] = temp;
MAX_HEAPIFY(a, 1, i - 1);
}
}

int main()
{
int n;
cout<<"Enter the size of the array"<<endl;
cin>>n;
int a[n];
cout<<"Enter the elements in the array"<<endl;
for (int i = 1; i <= n; i++)
{
cin>>a[i];
}
HEAPSORT(a, n);
cout<<":::::::SORTED FORM::::::"<<endl;
for (int i = 1; i <= n; i++)
{
cout<<a[i]<<endl;
}
}
OUTPUT:

RESULT:
EX NO:7 FIBONACCI HEAP IMPLEMENTATION
DATE:

AIM:
To write a program for Fibonacci heap implementation

ALGORITHM:

1.Start the program.


2.Declare the variables.
3.Create the functions to initialize methods.
4.Remove the topmost item (the largest) and replace it with the rightmost leaf.
5.Re-establish the heap.
6.Repeat steps 1 and 2 until there are no more items left in the heap.
7.The sorted elements are now stored in an array

PROGRAM:

#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
/* Node Declaration */
struct node
{
int n;
int degree;
node* parent;
node* child;
node* left;
node* right;
char mark;
char C; };
/* Class Declaration */
class FibonacciHeap
{
private:
int nH;
node *H;
public:
node* InitializeHeap();
int Fibonnaci_link(node*, node*, node*);
node *Create_node(int);
node *Insert(node *, node *);
node *Union(node *, node *);
node *Extract_Min(node *);
int Consolidate(node *);
int Display(node *);
node *Find(node *, int);
int Decrease_key(node *, int, int);
int Delete_key(node *,int);
int Cut(node *, node *, node *);
int Cascase_cut(node *, node *);
FibonacciHeap()
{
H = InitializeHeap();
} };
node* FibonacciHeap::InitializeHeap() {
node* np;
np = NULL;
return np; }
node* FibonacciHeap::Create_node(int value)
{
node* x = new node;
x->n = value; return x; }
node* FibonacciHeap::Insert(node* H, node* x)
{
x->degree = 0;
x->parent = NULL;
x->child = NULL;
x->left = x;
x->right = x;
x->mark = 'F';
x->C = 'N';
if (H != NULL)
{
(H->left)->right = x;
x->right = H;
x->left = H->left;
H->left = x;
if (x->n < H->n)
H = x; } else
{ H = x; }
nH = nH + 1;
return H; }
int FibonacciHeap::Fibonnaci_link(node* H1, node* y, node* z) {
(y->left)->right = y->right;
(y->right)->left = y->left;
if (z->right == z)
H1 = z;
y->left = y;
y->right = y;
y->parent = z;
if (z->child == NULL)
z->child = y;
y->right = z->child;
y->left = (z->child)->left;
((z->child)->left)->right = y;
(z->child)->left = y;
if (y->n < (z->child)->n)
z->child = y;
z->degree++;
}

/* Union Nodes in Fibonnaci Heap */


node* FibonacciHeap::Union(node* H1, node* H2)
{
node* np;
node* H = InitializeHeap();
H = H1;
(H->left)->right = H2;
(H2->left)->right = H;
np = H->left;
H->left = H2->left;
H2->left = np;
return H; }
x->parent = NULL;
x = np; } while (np != ptr); }
(z->left)->right = z->right;
(z->right)->left = z->left;
H1 = z->right;
if (z == z->right && z->child == NULL)
H = NULL; else {
H1 = z->right;
Consolidate(H1);
}
nH = nH - 1;
return p; }
/* Consolidate Node in Fibonnaci Heap */
int FibonacciHeap::Consolidate(node* H1)
{
int main()
{
int n, m, l;
FibonacciHeap fh;
node* p;
node* H;
H = fh.InitializeHeap();
while (1)
{ cout<<"----------------------------"<<endl;
cout<<"Operations on Binomial heap"<<endl;
cout<<"----------------------------"<<endl;
cout<<"1)Insert Element in the heap"<<endl;
cout<<"2)Extract Minimum key node"<<endl;
cout<<"3)Decrease key of a node"<<endl;
cout<<"4)Delete a node"<<endl;
cout<<"5)Display Heap"<<endl;
cout<<"6)Exit"<<endl;
cout<<"Enter Your Choice: ";
cin>>l;
switch(l)
{
case 1:
cout<<"Enter the element to be inserted: ";
cin>>m;
p = fh.Create_node(m);
H = fh.Insert(H, p);
break;
case 2:
p = fh.Extract_Min(H);
if (p != NULL)
cout<<"The node with minimum key: "<<p->n<<endl;
else
cout<<"Heap is empty"<<endl;
break;
case 3:
cout<<"Enter the key to be decreased: ";
cin>>m;
cout<<"Enter new key value: ";
cin>>l;
fh.Decrease_key(H, m, l);
break;
case 4:
cout<<"Enter the key to be deleted: ";
cin>>m;
fh.Delete_key(H, m);
break;
case 5:
cout<<"The Heap is: "<<endl;
fh.Display(H);
break;
case 6:
exit(1);
default:
cout<<"Wrong Choice"<<endl; }

} return 0;

}
OUTPUT:

RESULT:
EXNO :8 GRAPH TRAVERSALS
DATE:

AIM:
To write a program to implement graph traversals

ALGORITHM:

1. Insert the root node or starting node of a tree or a graph in the stack.
2. Pop the top item from the stack and add it to the visited list.
3. Find all the adjacent nodes of the node marked visited and add the ones
that are not yet visited, to the stack.
4.Repeat steps 2 and 3 until the stack is empty.
5.Stop the program.

PROGRAM 1:
DFS ALGORITHM
#include <iostream>
#include <list>
using namespace std;
//graph class for DFS travesal
class DFSGraph
{
int V; // No. of vertices
list<int> *adjList; // adjacency list
void DFS_util(int v, bool visited[]); // A function used by DFS
public:
// class Constructor
DFSGraph(int V)
{
this->V = V;
adjList = new list<int>[V];
}
// function to add an edge to graph
void addEdge(int v, int w){
adjList[v].push_back(w); // Add w to v’s list.
}

void DFS(); // DFS traversal function


};
void DFSGraph::DFS_util(int v, bool visited[])
{
// current node v is visited
visited[v] = true;
cout << v << " ";
// recursively process all the adjacent vertices of the node
list<int>::iterator i;
for(i = adjList[v].begin(); i != adjList[v].end(); ++i)
if(!visited[*i])
DFS_util(*i, visited);
}
// DFS traversal
void DFSGraph::DFS()
{
// initially none of the vertices are visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// explore the vertices one by one by recursively calling DFS_util
for (int i = 0; i < V; i++)
if (visited[i] == false)
DFS_util(i, visited);
}
int main()
{
// Create a graph
DFSGraph gdfs(5);
gdfs.addEdge(0, 1);
gdfs.addEdge(0, 2);
gdfs.addEdge(0, 3);
gdfs.addEdge(1, 2);
gdfs.addEdge(2, 4);
gdfs.addEdge(3, 3);
gdfs.addEdge(4, 4);
cout << "Depth-first traversal for the given graph:"<<endl;
gdfs.DFS();
return 0;
}
PROGRAM2:
BFS Implementation
#include&lt;iostream&gt;
#include &lt;list&gt;
using namespace std;
// a directed graph class
class DiGraph
{
int V; // No. of vertices

// Pointer to an array containing adjacency lists


list&lt;int&gt; *adjList;
public:
DiGraph(int V); // Constructor

// add an edge from vertex v to w


void addEdge(int v, int w);

// BFS traversal sequence starting with s -&gt;starting node


void BFS(int s);
};

DiGraph::DiGraph(int V)
{
this-&gt;V = V;
adjList = new list&lt;int&gt;[V];
}
void DiGraph::addEdge(int v, int w)
{
adjList[v].push_back(w); // Add w to v’s list.
}

void DiGraph::BFS(int s)
{
// initially none of the vertices is visited
bool *visited = new bool[V];
for(int i = 0; i &lt; V; i++)
visited[i] = false;

// queue to hold BFS traversal sequence


list&lt;int&gt; queue;

// Mark the current node as visited and enqueue it


visited[s] = true;
queue.push_back(s);

// iterator 'i' to get all adjacent vertices


list&lt;int&gt;::iterator i;
while(!queue.empty())
{
// dequeue the vertex
s = queue.front();
cout &lt;&lt; s &lt;&lt; " ";
queue.pop_front();

// get all adjacent vertices of popped vertex and process each if not already visited
for (i = adjList[s].begin(); i != adjList[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// main program
int main()
{
// create a graph
DiGraph dg(5);
dg.addEdge(0, 1);
dg.addEdge(0, 2);
dg.addEdge(0, 3);
dg.addEdge(1, 2);
dg.addEdge(2, 4);
dg.addEdge(3, 3);
dg.addEdge(4, 4);

cout &lt;&lt; "Breadth First Traversal for given graph (with 0 as starting node): "&lt;&lt;endl;
dg.BFS(0);

return 0;
}
OUTPUT:

Breadth-First Traversal for the given graph (with 0 as starting node):


01234

Depth-first traversal for the given graph:


01243

RESULT:
EX NO:9 SPANNING TREE IMPLEMENTATION
DATE

AIM:
To write a program to implement spanning tree.

ALGORITHM:

1. Initialize an array for storing the groups of the vertices.


2. Initialize an array for storing the edges of the graph with their weights.
3. Initialize the spanning tree as an empty array.
4. Put all vertices of the graph into different groups.
5. Sort the array of edges in increasing order of weights.
6. Continue step 7 till there is no more edge remaining in the sorted array of
edges
7. If the group of one node of an edge does not match the group of the other
node of the edge, add them both to the same group and add the edge to
the spanning tree array.
8. Iterate through the spanning-tree array and add the weights of the edges.

PROGRAM:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 1e6-1;
int root[MAX];
const int nodes = 4, edges = 5;
pair <long long, pair<int, int> > p[MAX];
int parent(int a)
{
while(root[a] != a)
{
root[a] = root[root[a]];
a = root[a];
}
return a;
}
void union_find(int a, int b)
{
int d = parent(a);
int e = parent(b);
root[d] = root[e];
}

long long kruskal()


{
int a, b;
long long cost, minCost = 0;
for(int i = 0 ; i < edges ; ++i)
{
a = p[i].second.first;
b = p[i].second.second;
cost = p[i].first;
if(parent(a) != parent(b))
minCost += cost;
union_find(a, b);
}
}
return minCost;
}

int main()
{
int x, y;
long long weight, cost, minCost;
for(int i = 0;i < MAX;++i)
{
root[i] = i;
}
p[0] = make_pair(10, make_pair(0, 1));
p[1] = make_pair(18, make_pair(1, 2));
p[2] = make_pair(13, make_pair(2, 3));
p[3] = make_pair(21, make_pair(0, 2));
p[4] = make_pair(22, make_pair(1, 3));
sort(p, p + edges);
minCost = kruskal();
cout << "Minimum cost is: "<< minCost << endl;
return 0;
}
OUTPUT:

The output for the given code segment is:


Minimum cost is: 4

RESULT:
EX NO:10 SHORTEST PATH ALGORITHMS
DATE:

AIM:
To write a program to implement shortest path algorithms.

ALGORITHM:

1.Calculate the path length of all the neighboring vertex from the current
vertex by adding the weight of the edge in the current vertex

2.Now, if the new path length is smaller than the previous path length then
replace it otherwise ignore it

3.Select the vertex with the smallest path length as the new current vertex
and go back to step 4.

4.Repeat this process until all the vertex are marked as visited.
PROGRAM:

#include<iostream>
#include<climits>
using namespace std;

int miniDist(int distance[], bool Tset[]) // finding minimum distance


{
int minimum=INT_MAX,ind;

for(int k=0;k<6;k++)
{
if(Tset[k]==false && distance[k]<=minimum)
{
minimum=distance[k];
ind=k;
}
}
return ind;
}

void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix


{
int distance[6]; // // array to calculate the minimum distance for each node
bool Tset[6];// boolean array to mark visited and unvisited for each node
for(int k = 0; k<6; k++)
{
distance[k] = INT_MAX;
Tset[k] = false;
}

distance[src] = 0; // Source vertex distance is set 0

for(int k = 0; k<6; k++)


{
int m=miniDist(distance,Tset);
Tset[m]=true;
for(int k = 0; k<6; k++)
{
// updating the distance of neighbouring vertex
if(!Tset[k] && graph[m][k] && distance[m]!=INT_MAX &&
distance[m]+graph[m][k]<distance[k])
distance[k]=distance[m]+graph[m][k];
}
}
cout<<"Vertex\t\tDistance from source vertex"<<endl;
for(int k = 0; k<6; k++)
{
char str=65+k;
cout<<str<<"\t\t\t"<<distance[k]<<endl;
}
}

int main()
{
int graph[6][6]={
{0, 1, 2, 0, 0, 0},
{1, 0, 0, 5, 1, 0},
{2, 0, 0, 2, 3, 0},
{0, 5, 2, 0, 2, 2},
{0, 1, 3, 2, 0, 1},
{0, 0, 0, 2, 1, 0}};
DijkstraAlgo(graph,0);
return 0;
}
OUTPUT:

Vertex Distance from source

A 0

B 1

C 2

D 4

E 2

F 3

RESULT:
EX NO:11 IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION

DATE:

AIM:

To write a program to implement matrix chain multiplication.

ALGORITHM:

1.start the program.


2.Declare the variables.
3.Every node is either red or black.
4.Every leaf (NULL) is black.
5.If a node is red, then both its children are black.
6.Every simple path from a node to a descendant leaf contains red tree.
7.stop the program.

PROGRAM:

#include<iostream>
#include<limits.h>

using namespace std;

// Matrix Ai has dimension p[i-1] x p[i] for i = 1..n

int MatrixChainMultiplication(int p[], int n)


{
int m[n][n];
int i, j, k, L, q;

for (i=1; i<n; i++)


m[i][i] = 0; //number of multiplications are 0(zero) when there is only one
matrix

//Here L is chain length. It varies from length 2 to length n.


for (L=2; L<n; L++)
{
for (i=1; i<n-L+1; i++)
{
j = i+L-1;
m[i][j] = INT_MAX; //assigning to maximum value

for (k=i; k<=j-1; k++)


{
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
{
m[i][j] = q; //if number of multiplications found less that number
will be updated.
}
}
}
}

return m[1][n-1]; //returning the final answer which is M[1][n]

int main()
{
int n,i;
cout<<"Enter number of matrices\n";
cin>>n;

n++;

int arr[n];

cout<<"Enter dimensions \n";

for(i=0;i<n;i++)
{
cout<<"Enter d"<<i<<" :: ";
cin>>arr[i];
}

int size = sizeof(arr)/sizeof(arr[0]);

cout<<"Minimum number of multiplications is


"<<MatrixChainMultiplication(arr, size));

return 0;
}
Output
Enter number of matrices
4
Enter dimensions
Enter d0 :: 10
Enter d1 :: 100
Enter d2 :: 20
Enter d3 :: 5
Enter d4 :: 80
Minimum number of multiplications is 19000

RESULT:
EX NO:12 ACTIVITY SELECTION AND HUFFMAN CODING
DATE: IMPLEMENTATION

AIM:

To write a program to implement activity selection and Huffman


coding.

ALGORITHM:

1.start the program.


2.Declare the variables.
3.Every node is either red or black.
4.Every leaf (NULL) is black.
5.If a node is red, then both its children are black.
6.Every simple path from a node to a descendant leaf contains red tree.
7.stop the program.

PROGRAM1:

ACTIVITY SELECTION
#include<iostream>
#include<algorithm>
using namespace std;
struct Activitiy {
int start, end;
};
bool comp(Activitiy act1, Activitiy act2) {
return (act1.end < act2.end);
}
void maxActivity(Activitiy act[], int n) {
sort(act, act+n, comp); //sort activities using compare function
cout << "Selected Activities are: " << endl;
int i = 0;// first activity as 0 is selected
cout << "Activity: " << i << " , Start: " <<act[i].start << " End: " << act[i].end
<<endl;
for (int j = 1; j < n; j++) { //for all other activities
if (act[j].start >= act[i].end) { //when start time is >=end time, print the
activity
cout << "Activity: " << j << " , Start: " <<act[j].start << " End: " <<
act[j].end <<endl;
i = j;
}
}
}
int main() {
Activitiy actArr[] = {{5,9},{1,2},{3,4},{0,6},{5,7},{8,9}};
int n = 6;
maxActivity(actArr,n);
return 0;
}
PROGRAM2:
HUFFMAN CODING
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;

#define EMPTY_STRING ""

// A Tree node
struct Node
{
char ch;
int freq;
Node *left, *right;
};

// Function to allocate a new tree node


Node* getNode(char ch, int freq, Node* left, Node* right)
{
Node* node = new Node();

node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;

return node;
}

// Comparison object to be used to order the heap


struct comp
{
bool operator()(const Node* l, const Node* r) const
{
// the highest priority item has the lowest frequency
return l->freq > r->freq;
}
};

// Utility function to check if Huffman Tree contains only a single node


bool isLeaf(Node* root) {
return root->left == nullptr && root->right == nullptr;
}

// Traverse the Huffman Tree and store Huffman Codes in a map.


void encode(Node* root, string str, unordered_map<char, string>
&huffmanCode)
{
if (root == nullptr) {
return;
}

// found a leaf node


if (isLeaf(root)) {
huffmanCode[root->ch] = (str != EMPTY_STRING) ? str : "1";
}

encode(root->left, str + "0", huffmanCode);


encode(root->right, str + "1", huffmanCode);
}

// Traverse the Huffman Tree and decode the encoded string


void decode(Node* root, int &index, string str)
{
if (root == nullptr) {
return;
}

// found a leaf node


if (isLeaf(root))
{
cout << root->ch;
return;
}

index++;

if (str[index] == '0') {
decode(root->left, index, str);
}
else {
decode(root->right, index, str);
}
}

// Builds Huffman Tree and decodes the given input text


void buildHuffmanTree(string text)
{
// base case: empty string
if (text == EMPTY_STRING) {
return;
}
// count the frequency of appearance of each character
// and store it in a map
unordered_map<char, int> freq;
for (char ch: text) {
freq[ch]++;
}

// Create a priority queue to store live nodes of the Huffman tree


priority_queue<Node*, vector<Node*>, comp> pq;

// Create a leaf node for each character and add it


// to the priority queue.
for (auto pair: freq) {
pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
}

// do till there is more than one node in the queue


while (pq.size() != 1)
{
// Remove the two nodes of the highest priority
// (the lowest frequency) from the queue

Node* left = pq.top(); pq.pop();


Node* right = pq.top(); pq.pop();

// create a new internal node with these two nodes as children and
// with a frequency equal to the sum of the two nodes' frequencies.
// Add the new node to the priority queue.

int sum = left->freq + right->freq;


pq.push(getNode('\0', sum, left, right));
}

// `root` stores pointer to the root of Huffman Tree


Node* root = pq.top();

// Traverse the Huffman Tree and store Huffman Codes


// in a map. Also, print them
unordered_map<char, string> huffmanCode;
encode(root, EMPTY_STRING, huffmanCode);

cout << "Huffman Codes are:\n" << endl;


for (auto pair: huffmanCode) {
cout << pair.first << " " << pair.second << endl;
}
cout << "\nThe original string is:\n" << text << endl;

// Print encoded string


string str;
for (char ch: text) {
str += huffmanCode[ch];
}

cout << "\nThe encoded string is:\n" << str << endl;
cout << "\nThe decoded string is:\n";

if (isLeaf(root))
{
// Special case: For input like a, aa, aaa, etc.
while (root->freq--) {
cout << root->ch;
}
}
else {
// Traverse the Huffman Tree again and this time,
// decode the encoded string
int index = -1;
while (index < (int)str.size() - 1) {
decode(root, index, str);
}
}
}

// Huffman coding algorithm implementation in C++


int main()
{
string text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);

return 0;
}
OUTPUT:
Selected Activities are:
Activity: 0 , Start: 1 End: 2
Activity: 1 , Start: 3 End: 4
Activity: 3 , Start: 5 End: 7
Activity: 5 , Start: 8 End: 9

Huffman Codes are:

c 11111
h 111100
f 11101
r 11100
t 11011
p 110101
i 1100
g 0011
l 00101
a 010
o 000
d 10011
H 00100
. 111101
s 0110
m 0111
e 110100
101
n 1000
u 10010

The original string is:


Huffman coding is a data compression algorithm.

The encoded string is:


0010010010111011110101110101000101111110001001111001000001110111
0001101010101011001101011011010101111110000111110101111001101000
1100110110000010001010100010100110001110011001101111110001111111
01

The decoded string is:


Huffman coding is a data compression algorithm.

RESULT:

You might also like