ADSLAB
ADSLAB
Palanchur, Chennai–600123
REG.NO:………………………………………..
NAME:………………………………….………
BONAFIDE CERTIFICATE
UNIVERSITY REGISTER NUMBER :
Palanchur, Chennai.
Algorithm Inorder(tree)
Algorithm Postorder(tree)
Algorithm Preorder(tree)
PROGRAM
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
/* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */
void printPostorder(struct Node* node)
{
if (node == NULL)
return;
printPostorder(node->left);
printPostorder(node->right);
cout << node->data << " ";
}
void printInorder(struct Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->data << " ";
printInorder(node->right);
}
void printPreorder(struct Node* node)
{
if (node == NULL)
return;
cout << node->data << " ";
printPreorder(node->left);
printPreorder(node->right);
}
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "\nPreorder traversal of binary tree is \n";
printPreorder(root);
cout << "\nInorder traversal of binary tree is \n";
printInorder(root);
cout << "\nPostorder traversal of binary tree is \n";
printPostorder(root);
return 0;
}
OUTPUT
RESULT:
Thus the C++ program for implementation of the recursive function for tree traversal was
created, executed and output was verified successfully.
EX. No. 1(B) Date: …………..
IMPLEMENTATION OF RECURSIVE FUNCTION FOR FIBONACCI
AIM
To write a program in C++ to implement the recursive function for fibonacci.
DESCRIPTION
1. Function is a block of statements that performs some operations. All C++ programs
have at least one function – function called “main()”. This function is entry-point of
your program.
2. A function declaration tells the compiler about a function’s name, return type, and
parameters. A function definition provides the actual body of the function.
PROGRAM
#include<iostream>
using namespace std;
int fibonacci(int n)
{
if((n==1)||(n==0))
{
return(n);
}
else
{
return(fibonacci(n-1)+fibonacci(n-2));
}
}
int main()
{
int n,i=0;
cout<<"\nHow many terms for Fibonacci Series :: ";
cin>>n;
cout<<"\nFibonacci Series for [ "<<n<<" ] Terms as follows :: \n\n";
while(i<n)
{
cout<<" "<<fibonacci(i);
i++;
}
cout<<"\n";
return 0;
}
OUTPUT
RESULT:
Thus the C++ program for implementation of the recursive function for fibonacci was created,
executed and output was verified successfully.
EX. No. 2(A) Date: …………..
IMPLEMENTATION OF ITERATION FUNCTION FOR TREE
TRAVERSAL
AIM
To write a program in C++ to implement the iteration function for tree traversal.
ALGORITHM
PROGRAM
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = new struct node;
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void iterativePreorder(node* root)
{
if (root == NULL)
return;
stack<node*> nodeStack;
nodeStack.push(root);
while (nodeStack.empty() == false)
{ struct node* node =
nodeStack.top(); printf("%d ", node-
>data); nodeStack.pop();
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left);
}
}
int main()
{
struct node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(2);
iterativePreorder(root);
return 0;
}
OUTPUT:
10 8 3 5 2 2
RESULT:
Thus the C++ program for implementation of iteration function for tree traversal was created,
executed and output was verified successfully.
EX. No. Date: …………..
IMPLEMENTION OF ITERATION FUNCTION FOR FIBONACCI
AIM
To write a program in C++ to implement the Iteration function for Fibonacci.
DESCRIPTION
The following C++ computes the Nth Fibonacci Number using this equation which runs O(1)
time and O(1) space (assuming the equation computation is O(1) constant))
PROGRAM
#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:
Thus the C++ program for implementation of Iteration function for Fibonacci was created,
executed and output was verified successfully.
EX. No. 3(A) Date: …………..
IMPLEMENTATION OF MERGE SORT
AIM
To write a program in C++ to implement the Implementation of Merge Sort.
DESCRIPTION
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = l+ (r-l)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
PROGRAM
#include <iostream>
using namespace std;
void merge(int array[], int const left, int const mid, int const right)
{
auto const subArrayOne = mid - left + 1;
auto const subArrayTwo = right - mid;
RESULT:
Thus the C++ program for implementation of Merge Sort was created, executed and output
was verified successfully.
EX. No. 3(B) Date: …………..
IMPLEMENTATION OF QUICK SORT
AIM
To write a program in C++ to implement the implementation of QuickSort.
DESCRIPTION
PROGRAM
#include <bits/stdc++.h>
using namespace std;
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
OUTPUT
Sorted array:
1 5 7 8 9 10
RESULT:
Thus the C++ program for implementation of QuickSort was created, executed and output was
verified successfully.
EX. No. 4 Date: …………..
IMPLEMENTION OF BINARY SEARCH TREE
AIM
To write a program in C++ to implement the Binary Search Tree.
DESCRIPTION
Binary Search Tree is a node-based binary tree data structure which has the following
properties:
1. The left subtree of a node contains only nodes with keys lesser than the node’s key.
2. The right subtree of a node contains only nodes with keys greater than the node’s key.
3. The left and right subtree each must also be a binary search tree.
PROGRAM
#include <iostream>
using namespace std;
class BST {
int data;
BST *left, *right;
public:
BST();
BST(int);
b.Inorder(root);
return 0;
}
OUTPUT
20
30
40
50
60
70
80
DELETION
#include <bits/stdc++.h>
using namespace std;
struct node {
int key;
struct node *left, *right;
};
return node;
}
struct node* minValueNode(struct node* node)
{
struct node* current = node;
while (current && current->left != NULL)
current = current->left;
return current;
}
struct node* deleteNode(struct node* root, int key)
{
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if (root->left==NULL and root->right==NULL)
return NULL;
else if (root->left == NULL)
{ struct node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{ struct node* temp = root->left;
free(root);
return temp;
}
struct node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
int main()
{
struct node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
cout << "Inorder traversal of the given tree \n";
inorder(root);
cout << "\nDelete 20\n";
root = deleteNode(root, 20);
cout << "Inorder traversal of the modified tree \n";
inorder(root);
cout << "\nDelete 30\n";
root = deleteNode(root, 30);
cout << "Inorder traversal of the modified tree \n";
inorder(root);
cout << "\nDelete 50\n";
root = deleteNode(root, 50);
cout << "Inorder traversal of the modified tree \n";
inorder(root);
return 0;
}
OUTPUT:
RESULT:
Thus the C++ program for implementation of Binary Search Tree was created, executed and
output was verified successfully.
EX. No. 5 Date: …………..
IMPLEMENTION OF RED-BLACK TREE
AIM
To write a program in C++ to implement the Red-Black Tree.
DESCRIPTION
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(p->key==x)
found=1;
if(found==0)
{
if(p->key<x)
p=p->right;
else
p=p->left;
}
}
if(found==0)
{
cout<<"\nElement Not Found.";
return ;
}
else
{
cout<<"\nDeleted Element: "<<p->key;
cout<<"\nColour: ";
if(p->color=='b')
cout<<"Black\n";
else
cout<<"Red\n";
if(p->parent!=NULL)
cout<<"\nParent: "<<p->parent->key;
else
cout<<"\nThere is no parent of the node. ";
if(p->right!=NULL)
cout<<"\nRight Child: "<<p->right->key;
else
cout<<"\nThere is no right child of the node. ";
if(p->left!=NULL)
cout<<"\nLeft Child: "<<p->left->key;
else
cout<<"\nThere is no left child of the node. ";
cout<<"\nNode Deleted.";
if(p->left==NULL||p->right==NULL)
y=p;
else
y=successor(p);
if(y->left!=NULL)
q=y->left;
else
{
if(y->right!=NULL)
q=y->right;
else
q=NULL;
}
if(q!=NULL)
q->parent=y->parent;
if(y->parent==NULL)
root=q;
else
{
if(y==y->parent->left)
y->parent->left=q;
else
y->parent->right=q;
}
if(y!=p)
{
p->color=y->color;
p->key=y->key;
}
if(y->color=='b')
delfix(q);
}
}
void RBtree::disp()
{
display(root);
}
void RBtree::display(node *p)
{
if(root==NULL)
{
cout<<"\nEmpty Tree.";
return ;
}
if(p!=NULL)
{
cout<<"\n\t 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;
if(p->left)
{
cout<<"\n\nLeft:\n";
display(p->left);
}
/*else
cout<<"\nNo Left Child.\n";*/
if(p->right)
{
cout<<"\n\nRight:\n";
display(p->right);
}
/*else
cout<<"\nNo Right Child.\n"*/
}
}
void RBtree::search()
{
if(root==NULL)
{
cout<<"\nEmpty Tree\n" ;
return ;
}
int x;
cout<<"\n Enter key of the node to be searched: ";
cin>>x;
node *p=root;
int found=0;
while(p!=NULL&& found==0)
{
if(p->key==x)
found=1;
if(found==0)
{
if(p->key<x)
p=p->right;
else
p=p->left;
}
}
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:
Thus the C++ program for implementation of the Red-Black Tree was created, executed and
output was verified successfully.
EX. No. 6 Date: …………..
IMPLEMENTION OF HEAP
AIM
To write a program in C++ to implement the Heap Implementation.
DESCRIPTION
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root
must be minimum among all keys present in Binary Heap. The same property must be
recursively true for all nodes in Binary Tree. Max Binary Heap is similar to MinHeap.
PROGRAM
#include <iostream>
#include <cstdlib>
#include <vector>
#include <iterator>
using namespace std;
class BHeap {
private:
vector <int> heap;
int l(int parent);
int r(int parent);
int par(int child);
void heapifyup(int index);
void heapifydown(int index);
public:
BHeap() {}
void Insert(int element);
void DeleteMin();
int ExtractMin();
void showHeap();
int Size();
};
int main()
{ BHeap h;
while (1) {
cout<<"1.Insert Element"<<endl;
cout<<"2.Delete Minimum Element"<<endl;
cout<<"3.Extract Minimum Element"<<endl;
cout<<"4.Show Heap"<<endl;
cout<<"5.Exit"<<endl;
int c, e;
cout<<"Enter your choice: ";
cin>>c;
switch(c)
{ case 1:
cout<<"Enter the element to be inserted: ";
cin>>e;
h.Insert(e);
break;
case 2:
h.DeleteMin();
break;
case 3:
if (h.ExtractMin() == -1)
{ cout<<"Heap is Empty"<<endl;
}
else
cout<<"Minimum Element: "<<h.ExtractMin()<<endl;
break;
case 4:
cout<<"Displaying elements of Hwap: ";
h.showHeap();
break;
case 5:
exit(1);
default:
cout<<"Enter Correct Choice"<<endl;
} }
return 0;
}
int BHeap::Size()
{ return
heap.size();
}
void BHeap::Insert(int ele)
{ heap.push_back(ele);
heapifyup(heap.size() -1);
}
void BHeap::DeleteMin()
{ if (heap.size() == 0) {
cout<<"Heap is Empty"<<endl;
return;
}
heap[0] = heap.at(heap.size() - 1);
heap.pop_back();
heapifydown(0);
cout<<"Element Deleted"<<endl;
}
int BHeap::ExtractMin()
{ if (heap.size() == 0) {
return -1;
}
else
return heap.front();
}
void BHeap::showHeap() {
vector <int>::iterator pos = heap.begin();
cout<<"Heap --> ";
while (pos != heap.end())
{ cout<<*pos<<" ";
pos++;
}
cout<<endl;
}
int BHeap::l(int parent)
{ int l = 2 * parent + 1;
if (l < heap.size())
return l;
else
return -1;}
int BHeap::r(int parent)
{ int r = 2 * parent + 2;
if (r < heap.size())
return r;
else
return -1;}
int BHeap::par(int child)
{ int p = (child - 1)/2;
if (child == 0)
return -1;
else
return p;}
void BHeap::heapifyup(int in) {
if (in >= 0 && par(in) >= 0 && heap[par(in)] > heap[in])
{ int temp = heap[in];
heap[in] = heap[par(in)];
heap[par(in)] = temp;
heapifyup(par(in));
}}
void BHeap::heapifydown(int in)
{ int child = l(in);
int child1 = r(in);
if (child >= 0 && child1 >= 0 && heap[child] > heap[child1])
{ child = child1; }
if (child > 0 && heap[in] > heap[child])
{ int t = heap[in];
heap[in] = heap[child];
heap[child] = t;
heapifydown(child);
}
}
OUTPUT
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 2
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 3
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 7
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 1
Enter the element to be inserted: 6
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 4
Displaying elements of Hwap: Heap --> 2 3 7 6
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 3
Minimum Element: 2
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 3
Minimum Element: 2
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 2
Element Deleted
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 4
Displaying elements of Hwap: Heap --> 3 6 7
1. Insert Element
2. Delete Minimum Element
3. Extract Minimum Element
4. Show Heap
5.Exit
Enter your choice: 5
RESULT:
Thus the C++ program for implementation of Heap was created, executed and output was
verified successfully.
EX. No. 7 Date: …………..
IMPLEMENTION OF FIBONACCI HEAP
AIM
To write a program in C++ to implement the Fibonacci Heap.
DESCRIPTION
1. It is a set of min heap-ordered trees. (i.e. The parent is always smaller than the
children.)
2. A pointer is maintained at the minimum element node.
3. It consists of a set of marked nodes. (Decrease key operation)
4. The trees within a Fibonacci heap are unordered but rooted.
PROGRAM
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
struct node
{
int n;
int degree;
node* parent;
node* child;
node* left;
node* right;
char mark;
char C;
};
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;
}
RESULT:
Thus the C++ program for implementation of Fibonacci Heap was created, executed and output
was verified successfully.
EX. No. 8(A) Date: …………..
GRAPH TRAVERSAL (BFS)
AIM
To write a program in C++ to implement the Graph Traversal (BFS).
DESCRIPTION
1. Start by putting any one of the graph's vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited
list to the back of the queue.
4. Keep repeating steps 2 and 3 until the queue is empty.
PROGRAM
#include<bits/stdc++.h>
using namespace std;
class Graph
{
int V; // No. of vertices
vector<list<int>> adj;
public:
Graph(int V); // Constructor
void addEdge(int v, int w);
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj.resize(V);
}
void Graph::BFS(int s)
{
vector<bool> visited;
visited.resize(V,false);
list<int> queue;
visited[s] = true;
queue.push_back(s);
while(!queue.empty())
{
s = queue.front();
cout << s << " ";
queue.pop_front();
for (auto adjecent: adj[s])
{
if (!visited[adjecent])
{
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}
int main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
return 0;
}
OUTPUT
RESULT:
Thus the C++ program for implementation of Graph Traversal (BFS) was created, executed
and output was verified successfully.
EX. No. 8(B) Date: …………..
GRAPH TRAVERSAL (DFS)
AIM
To write a program in C++ to implement the Graph Traversal (DFS).
DESCRIPTION
1. Create a recursive function that takes the index of the node and a visited array.
2. Mark the current node as visited and print the node.
3. Traverse all the adjacent and unmarked nodes and call the recursive function with the
index of the adjacent node.
PROGRAM
#include <bits/stdc++.h>
using namespace std;
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
void addEdge(int v, int w);
void DFS(int v);
};
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::DFS(int v)
{
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
int main()
{
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Depth First Traversal"
" (starting from vertex 2) \n";
g.DFS(2);
return 0;
}
OUTPUT:
RESULT:
Thus the C++ program for implementation of Graph Traversal (DFS) was created, executed
and output was verified successfully.
EX. No. 9 Date: …………..
IMPLEMENTION OF SPANNING TREE
AIM
To write a program in C++ to implement the Spanning Tree.
DESCRIPTION
PROGRAM
#include <bits/stdc++.h>
using namespace std;
class DSU {
int* parent;
int* rank;
public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];
if (s1 != s2) {
if (rank[s1] < rank[s2])
{ parent[s1] = s2;
rank[s2] += rank[s1];
}
else {
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
};
class Graph
{ vector<vector<int> >
edgelist; int V;
public:
Graph(int V) { this->V = V; }
void kruskals_mst()
{
sort(edgelist.begin(), edgelist.end());
DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl;
for (auto edge : edgelist)
{ int w = edge[0];
int x = edge[1];
int y = edge[2];
if (s.find(x) != s.find(y))
{ s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}
}
cout << "Minimum Cost Spanning Tree: " << ans;
}
};
int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);
}
g.kruskals_mst();
return 0;
}
OUTPUT
RESULT:
Thus the C++ program for implementation of Spanning Tree was created, executed and output
was verified successfully.
EX. No. 10(A) Date: …………..
SHORTEST PATH ALGORITHMS (DIJKSTRA'S ALGORITHM)
AIM
To write a program in C++ to implement the Dijkstra's algorithm.
DESCRIPTION
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this
set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn’t include all vertices
a) Pick a vertex u which is not there in sptSet and has minimum distance value.
b) Include u to sptSet.
c) Update distance value of all adjacent vertices of u. To update the distance values,
iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance
value of u (from source) and weight of edge u-v, is less than the distance value of v,
then update the distance value of v.
PROGRAM
#include <limits.h>
#include <stdio.h>
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{ int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX
&& dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main()
{
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);
return 0;
}
OUTPUT
RESULT:
Thus the C++ program for implementation of Dijkstra's algorithm was created, executed and
output was verified successfully.
EX. No. 10(B) Date: …………..
SHORTEST PATH ALGORITHMS (BELLMAN FORD ALGORITHM)
AIM
To write a program in C++ to implement the Bellman Ford Algorithm.
DESCRIPTION
1) This step initializes distances from source to all vertices as infinite and distance to source
itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src
is source vertex.
2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of
vertices in given graph.
a) Do following for each edge u-v
If dist[v] > dist[u] + weight of edge uv, then update dist[v]
dist[v] = dist[u] + weight of edge uv
3) This step reports if there is a negative weight cycle in graph. Do following for each edge u-
If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle”
The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative
weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex,
then there is a negative weight cycle
PROGRAM
#include <bits/stdc++.h>
using namespace std;
void BellmanFord(int graph[][3], int V, int E,
int src)
{
int dis[V];
for (int i = 0; i < V; i++)
dis[i] = INT_MAX;
dis[src] = 0;
for (int i = 0; i < V - 1; i++)
{ for (int j = 0; j < E; j++) {
if (dis[graph[j][0]] != INT_MAX && dis[graph[j][0]] + graph[j][2] <
dis[graph[j][1]])
dis[graph[j][1]] =
dis[graph[j][0]] + graph[j][2];
}
}
for (int i = 0; i < E; i++)
{ int x = graph[i][0];
int y = graph[i][1];
int weight = graph[i][2];
if (dis[x] != INT_MAX &&
dis[x] + weight < dis[y])
cout << "Graph contains negative"
" weight cycle"
<< endl;
}
OUTPUT:
Vertex Distance from Source
0 0
1 -1
2 2
3 -2
4 1
RESULT:
Thus the C++ program for implementation of Bellman Ford Algorithm was created, executed
and output was verified successfully.
EX. No. 11 Date: …………..
IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION
AIM
To write a program in C++ to implement the matrix chain multiplication.
DESCRIPTION
1. m[1,1] tells us about the operation of multiplying matrix A with itself which will be 0.
So fill all the m[i,i] as 0.
2. m[1,2] We are multiplying two matrices A and B. Operations will be 5*4*6=120.
3. m[2,3] We are multiplying B and C now. Operations will be 4*6*2=48
4. m[3,4] can be also filled in the same way.
PROGRAM
#include<bits/stdc++.h>
using namespace std;
int MatrixChainOrder(int p[], int n)
{
int m[n][n];
int i, j, k, L, q;
}
OUTPUT:
158 operations
RESULT:
Thus the C++ program for implementation of matrix chain multiplication was created, executed
and output was verified successfully.
EX. No. 12(A) Date: …………..
ACTIVITY SELECTION IMPLEMENTATION
AIM
To write a program in C++ to implement the activity selection.
DESCRIPTION
PROGRAM
#include <bits/stdc++.h>
using namespace std;
void printMaxActivities(int s[], int f[], int n)
{
int i, j;
OUTPUT
Following activities are selected n0 1 3 4
RESULT:
Thus the C++ program for implementation of Activity Selection was created, executed and
output was verified successfully.
EX. No. 12(B) Date: …………..
HUFFMAN CODING IMPLEMENTATION
AIM
To write a program in C++ to implement the Huffman Coding.
DESCRIPTION
1. Create a leaf node for each unique character and build a min heap of all leaf nodes (Min
Heap is used as a priority queue. The value of frequency field is used to compare two
nodes in min heap. Initially, the least frequent character is at root)
2. Extract two nodes with the minimum frequency from the min heap.
3. Create a new internal node with a frequency equal to the sum of the two nodes
frequencies. Make the first extracted node as its left child and the other extracted node
as its right child. Add this node to the min heap.
4. Repeat steps#2 and #3 until the heap contains only one node. The remaining node is the
root node and the tree is complete
PROGRAM
#include <iostream>
#include <cstdlib>
using namespace std;
#define MAX_TREE_HT 100
struct MinHeapNode {
char data;
unsigned freq;
struct MinHeapNode *left, *right;
};
struct MinHeap
{ unsigned size;
unsigned capacity;
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array
= (struct MinHeapNode**)malloc(minHeap->
capacity * sizeof(struct MinHeapNode*));
return minHeap;
}
if (smallest != idx)
{ swapMinHeapNode(&minHeap-
>array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
++minHeap->size;
int i = minHeap->size - 1;
minHeap->array[i] = minHeapNode;
}
void buildMinHeap(struct MinHeap* minHeap)
int n = minHeap->size - 1;
int i;
cout<<"\n";
}
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
{
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
while (!isSizeOne(minHeap)) {
left = extractMin(minHeap);
right = extractMin(minHeap);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
if (root->left) {
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
if (root->right) {
arr[top] = 1;
printCodes(root->right, arr, top + 1);
}
if (isLeaf(root)) {
int main()
{
return 0;
}
OUTPUT:
f: 0
c: 100
d: 101
a: 1100
b: 1101
e: 111
RESULT:
Thus the C++ program for implementation of Huffman Coding was created, executed and
output was verified successfully.