0% found this document useful (0 votes)
23 views109 pages

CP4161 Adsa Lab Record

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 109

INDEX

PAGE
EX.NO DATE EXPERIMENT NAME MARKS SIGN
NO

1 Implementation of recursive function


for tree traversal and Fibonacci

2 Implementation of iteration function


for tree traversal and Fibonacci
Implementation of merge sort
3 and quick sort

4 Implementation of a binary search


tree
5
Implementation of red-black tree

6
Implementation of heap

7 Implementation of Fibonacci Heap

8 Graph traversals

9 Implementation of spanning tree

10 Shortest path algorithms (dijkstra’s


algorithm, bellman ford algorithm

11 Implementation of matrix chain


multiplication
12 Implementation of activity selection and
huffman coding

1
EX.NO:1 IMPLEMENTATION OF RECURSIVE FUNCTION FOR TREE TRAVERSAL AND

DATE: FABONACCI

AIM:

Write a program to implementation of recursive function for tree traversal and Fibonacci in C++
language.

PROGRAM:

RECURSIVE OF TREE TRVERSAL:

INORDER TRAVERSALS:

#include <iostream>
using namespace std;

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};

/* Given a binary tree, print its nodes in inorder*/


void printInorder(struct Node* node)
{
if (node == NULL)
return;

/* first recur on left child */


printInorder(node->left);

/* then print the data of node */


cout << node->data << " ";

/* now recur on right child */


printInorder(node->right);
}

/* Driver program to test above functions*/


int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
2
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "\nInorder traversal of binary tree is \n";


printInorder(root);

return 0;
}

PREORDER TRAVERSALS:

#include <iostream>
using namespace std;

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};

/* Given a binary tree, print its nodes in preorder*/


void printPreorder(struct Node* node)
{
if (node == NULL)
return;

/* first print data of node */


cout << node->data << " ";

/* then recur on left subtree */


printPreorder(node->left);

/* now recur on right subtree */


printPreorder(node->right);
}

/* Driver program to test above functions*/


int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "\nPreorder traversal of binary tree is \n";


printPreorder(root);
3
return 0;
}

POSTORDER TRAVERSALS:

#include <iostream>
using namespace std;

/* A binary tree node has data, pointer to left child


and a pointer to right child */
struct Node {
int data;
struct Node *left, *right;
Node(int data)
{
this->data = data;
left = right = NULL;
}
};

/* Given a binary tree, print its nodes according to the


"bottom-up" postorder traversal. */
void printPostorder(struct Node* node)
{
if (node == NULL)
return;

// first recur on left subtree


printPostorder(node->left);

// then recur on right subtree


printPostorder(node->right);

// now deal with the node


cout << node->data << " ";
}
/* Driver program to test above functions*/
int main()
{
struct Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);

cout << "\nPostorder traversal of binary tree is \n";


printPostorder(root);

return 0;
}
RECURSIVE OF FIBONACCI:

4
#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:

Inorder traversal of binary tree is

42513

Preorder traversal of binary tree is

12453

Postorder traversal of binary tree is

45231

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

RESULTS:

Thus, the program is implementation and verified in recursive function for tree traversal and
Fibonacci in C++ language.

5
EX.NO:2 IMPLEMENTATION OF ITERATION FUNCTION FOR TREE TRAVERSAL
AND

DATE: FABONACCI

AIM:

Write a program to implementation of iteration function for tree traversal and Fibonacci in C++
language.

PROGRAM:

ITERATION OF TREE TRVERSAL:

INORDER TRAVERSALS:

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

// Data structure to store a binary tree node


struct Node
{
int data;
Node *left, *right;

Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};

// Iterative function to perform inorder traversal on the tree


void inorderIterative(Node* root)
{
// create an empty stack
stack<Node*> stack;

// start from the root node (set current node to the root node)
Node* curr = root;

// if the current node is null and the stack is also empty, we are done
while (!stack.empty() || curr != nullptr)
{
// if the current node exists, push it into the stack (defer it)
// and move to its left child
if (curr != nullptr)
{
stack.push(curr);
curr = curr->left;
}
6
else {
// otherwise, if the current node is null, pop an element from the stack,
// print it, and finally set the current node to its right child
curr = stack.top();
stack.pop();
cout << curr->data << " ";

curr = curr->right;
}
}
}

int main()
{

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;
}

PREORDER TRAVERSALS:

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

// Data structure to store a binary tree node


struct Node
{
int data;
Node *left, *right;

Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};

// Iterative function to perform preorder traversal on the tree


void preorderIterative(Node* root)
{
// return if the tree is empty
if (root == nullptr)
7
return;

// create an empty stack and push the root node


stack<Node*> stack;
stack.push(root);

// loop till stack is empty


while (!stack.empty())
{
// pop a node from the stack and print it
Node* curr = stack.top();
stack.pop();

cout << curr->data << " ";

// push the right child of the popped node into the stack
if (curr->right) {
stack.push(curr->right);
}

// push the left child of the popped node into the stack
if (curr->left) {
stack.push(curr->left);
}

// the right child must be pushed first so that the left child
// is processed first (LIFO order)
}
}

int main()
{

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);

preorderIterative(root);

return 0;
}

POSTORDER TRAVERSALS:

#include <iostream>
#include <stack>
using namespace std;
8
// Data structure to store a binary tree node
struct Node
{
int data;
Node *left, *right;

Node(int data)
{
this->data = data;
this->left = this->right = nullptr;
}
};

// Iterative function to perform postorder traversal on the tree


void postorderIterative(Node* root)
{
// return if the tree is empty
if (root == nullptr) {
return;
}

// create an empty stack and push the root node


stack<Node*> s;
s.push(root);

// create another stack to store postorder traversal


stack<int> out;

// loop till stack is empty


while (!s.empty())
{
// pop a node from the stack and push the data into the output stack
Node* curr = s.top();
s.pop();

out.push(curr->data);

// push the left and right child of the popped node into the stack
if (curr->left) {
s.push(curr->left);
}

if (curr->right) {
s.push(curr->right);
}
}

// print postorder traversal


while (!out.empty())
{
cout << out.top() << " ";
out.pop();

9
}
}

int main()
{

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);

postorderIterative(root);

return 0;
}
ITERATION OF FIBONACCI:

#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;
}
return 0;
}

OUTPUT:
10
Inorder traversal of binary tree is

42175836

Preorder traversal of binary tree is

12435786

Postorder traversal of binary tree is

42785631
Enter the number : 10
The fibonacci series : 0 1 1 2 3 5 8 13 21 34

RESULTS:

Thus, the program is implementation and verified in iteration function for tree traversal and
Fibonacci in C++ language.

11
EX.NO:3 IMPLEMENTATION OF MERGE SORT AND QUICK SORT

DATE:

AIM:

Write a program to implementation of Merge Sort and Quick Sort in C++ language.

PROGRAM:

MERGE SORT PROGRAM:

#include <iostream>

using namespace std;

// A function to merge the two half into a sorted data.

void Merge(int *a, int low, int high, int mid)

// We have low to mid and mid+1 to high already sorted.

int i, j, k, temp[high-low+1];

i = low;

k = 0;

j = mid + 1;

// Merge the two parts into temp[].

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

if (a[i] < a[j])

temp[k] = a[i];

k++;

i++;

12
else

temp[k] = a[j];

k++;

j++;

// Insert all the remaining values from i to mid into temp[].

while (i <= mid)

temp[k] = a[i];

k++;

i++;

// Insert all the remaining values from j to high into temp[].

while (j <= high)

temp[k] = a[j];

k++;

j++;

// Assign sorted data stored in temp[] to a[].

for (i = low; i <= high; i++)

a[i] = temp[i-low];

13
}

// A function to split array into two parts.

void MergeSort(int *a, int low, int high)

int mid;

if (low < high)

mid=(low+high)/2;

// Split the data into two half.

MergeSort(a, low, mid);

MergeSort(a, mid+1, high);

// Merge them to get sorted output.

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<<": ";

14
cin>>arr[i];

MergeSort(arr, 0, n-1);

// Printing the sorted data.

cout<<"\nSorted Data ";

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

cout<<"->"<<arr[i];

return 0;

QUICK SORT PORGRAM:

#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);
15
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:

MERGE SORT 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
16
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

QUICK SORT OUTPUT:

How many elements?6

Enter array elements:9 15 6 7 10 12

Array after sorting:6 7 9 10 12 15

RESULTS:

Thus, the program is implementation and verified in Merge Sort and Quick Sort in C++ language.

17
EX.NO:4 IMPLEMENTATION OF A BINARY SEARCH TREE

DATE:

AIM:

Write a program to implementation of a Binary Search Tree in C++ language.

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

18
{
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

19
{
int depth = 0;
nod *temp = new nod;
temp = root;
while(temp != NULL)
{
depth++;
if(temp→info == data)
{
cout<<"\nData found at depth: "<<depth<<endl;
return;
}
else if(temp→info > data)
temp = temp→l;
else
temp = temp→r;
}
cout<<"\n Data not found"<<endl;
return;
}
void BST::insert(nod *tree, nod *newnode)
{
if (r == NULL)
{
r = new nod;
r→info = newnode→info;
r→l= NULL;
r→r= NULL;
cout<<"Root Node is Added"<<endl;
return;
}
if (tree→info == newnode→info)
{
cout<<"Element already in the tree"<<endl;
return;
}
if (tree→info > newnode→info)

20
{
if (tree→l != NULL)
{
insert(tree→l, newnode);
}
else
{
tree→l= newnode;
(tree→l)→l = NULL;
(tree→l)→r= NULL;
cout<<"Node Added To Left"<<endl;
return;
}
}
else
{
if (tree→r != NULL)
{
insert(tree→r, newnode);
}
else
{
tree→r = newnode;
(tree→r)→l= NULL;
(tree→r)→r = NULL;
cout<<"Node Added To Right"<<endl;
return;
}
}
}
void BST::del(int i)
{
nod *par, *loc;
if (r == NULL)
{
cout<<"Tree empty"<<endl;
return;

21
}
find(i, &par, &loc);
if (loc == NULL)
{
cout<<"Item not present in tree"<<endl;
return;
}
if (loc→l == NULL && loc→r == NULL)
{
casea(par, loc);
cout<<"item deleted"<<endl;
}
if (loc→l!= NULL && loc→r == NULL)
{
caseb(par, loc);
cout<<"item deleted"<<endl;
}
if (loc→l== NULL && loc→r != NULL)
{
caseb(par, loc);
cout<<"item deleted"<<endl;
}
if (loc→l != NULL && loc→r != NULL)
{
casec(par, loc);
cout<<"item deleted"<<endl;
}
free(loc);
}
void BST::casea(nod *par, nod *loc )
{
if (par == NULL)
{
r= NULL;
}
else
{

22
if (loc == par→l)
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;

23
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;

24
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<<" ";
}

25
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;

26
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;
}
}
}

27
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 : 1
Enter the number to be inserted : 5
Node Added To Left
1.Insert Element
2.Delete Element
3.Search Element
28
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 : 4
Node Added To Left
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 : 3
Search:
7
Data found at depth: 2
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 : 3
Search:
1
Data not found
1.Insert Element
2.Delete Element
3.Search Element
4.Inorder Traversal
5.Preorder Traversal

29
6.Postorder Traversal
7.Display the tree
8.Quit
Enter your choice : 4
Inorder Traversal of BST:
4567
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 : 5
Preorder Traversal of BST:
6547
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 : 6
Postorder Traversal of BST:
4576
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

30
Display BST:
7
Root→: 6
5
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 : 2
Enter the number to be deleted : 1
Item not present in tree
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 : 5
Preorder Traversal of BST:
6547
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

31
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 :

RESULTS:

Thus, the program is implementation and verified in a Binary Search Tree in C++ language.

32
EX.NO:5 IMPLEMENTATION OF RED-BLACK TREE

DATE:

AIM:

Write a program to implementation of Red-Black Tree in C++ language.

PROGRAM:

// Red Black Tree implementation in C++

// Author: Algorithm Tutor

// Tutorial URL: https://algorithmtutor.com/Data-Structures/Tree/Red-Black-Trees/

#include <iostream>

using namespace std;

// data structure that represents a node in the tree

struct Node {

int data; // holds the key

Node *parent; // pointer to the parent

Node *left; // pointer to left child

Node *right; // pointer to right child

int color; // 1 -> Red, 0 -> Black

};

typedef Node *NodePtr;

// class RBTree implements the operations in Red Black Tree

class RBTree {

private:

NodePtr root;
33
NodePtr TNULL;

// initializes the nodes with appropirate values

// all the pointers are set to point to the null pointer

void initializeNULLNode(NodePtr node, NodePtr parent) {

node->data = 0;

node->parent = parent;

node->left = nullptr;

node->right = nullptr;

node->color = 0;

void preOrderHelper(NodePtr node) {

if (node != TNULL) {

cout<<node->data<<" ";

preOrderHelper(node->left);

preOrderHelper(node->right);

void inOrderHelper(NodePtr node) {

if (node != TNULL) {

inOrderHelper(node->left);

cout<<node->data<<" ";

inOrderHelper(node->right);

void postOrderHelper(NodePtr node) {


34
if (node != TNULL) {

postOrderHelper(node->left);

postOrderHelper(node->right);

cout<<node->data<<" ";

NodePtr searchTreeHelper(NodePtr node, int key) {

if (node == TNULL || key == node->data) {

return node;

if (key < node->data) {

return searchTreeHelper(node->left, key);

return searchTreeHelper(node->right, key);

// fix the rb tree modified by the delete operation

void fixDelete(NodePtr x) {

NodePtr s;

while (x != root && x->color == 0) {

if (x == x->parent->left) {

s = x->parent->right;

if (s->color == 1) {

// case 3.1

s->color = 0;

x->parent->color = 1;

leftRotate(x->parent);
35
s = x->parent->right;

if (s->left->color == 0 && s->right->color == 0) {

// case 3.2

s->color = 1;

x = x->parent;

} else {

if (s->right->color == 0) {

// case 3.3

s->left->color = 0;

s->color = 1;

rightRotate(s);

s = x->parent->right;

// case 3.4

s->color = x->parent->color;

x->parent->color = 0;

s->right->color = 0;

leftRotate(x->parent);

x = root;

} else {

s = x->parent->left;

if (s->color == 1) {

// case 3.1

s->color = 0;

x->parent->color = 1;
36
rightRotate(x->parent);

s = x->parent->left;

if (s->right->color == 0 && s->right->color == 0) {

// case 3.2

s->color = 1;

x = x->parent;

} else {

if (s->left->color == 0) {

// case 3.3

s->right->color = 0;

s->color = 1;

leftRotate(s);

s = x->parent->left;

// case 3.4

s->color = x->parent->color;

x->parent->color = 0;

s->left->color = 0;

rightRotate(x->parent);

x = root;

x->color = 0;

37
void rbTransplant(NodePtr u, NodePtr v){

if (u->parent == nullptr) {

root = v;

} else if (u == u->parent->left){

u->parent->left = v;

} else {

u->parent->right = v;

v->parent = u->parent;

void deleteNodeHelper(NodePtr node, int key) {

// find the node containing key

NodePtr z = TNULL;

NodePtr x, y;

while (node != TNULL){

if (node->data == key) {

z = node;

if (node->data <= key) {

node = node->right;

} else {

node = node->left;

if (z == TNULL) {
38
cout<<"Couldn't find key in the tree"<<endl;

return;

y = z;

int y_original_color = y->color;

if (z->left == TNULL) {

x = z->right;

rbTransplant(z, z->right);

} else if (z->right == TNULL) {

x = z->left;

rbTransplant(z, z->left);

} else {

y = minimum(z->right);

y_original_color = y->color;

x = y->right;

if (y->parent == z) {

x->parent = y;

} else {

rbTransplant(y, y->right);

y->right = z->right;

y->right->parent = y;

rbTransplant(z, y);

y->left = z->left;

y->left->parent = y;

y->color = z->color;

}
39
delete z;

if (y_original_color == 0){

fixDelete(x);

// fix the red-black tree

void fixInsert(NodePtr k){

NodePtr u;

while (k->parent->color == 1) {

if (k->parent == k->parent->parent->right) {

u = k->parent->parent->left; // uncle

if (u->color == 1) {

// case 3.1

u->color = 0;

k->parent->color = 0;

k->parent->parent->color = 1;

k = k->parent->parent;

} else {

if (k == k->parent->left) {

// case 3.2.2

k = k->parent;

rightRotate(k);

// case 3.2.1

k->parent->color = 0;

k->parent->parent->color = 1;

leftRotate(k->parent->parent);

}
40
} else {

u = k->parent->parent->right; // uncle

if (u->color == 1) {

// mirror case 3.1

u->color = 0;

k->parent->color = 0;

k->parent->parent->color = 1;

k = k->parent->parent;

} else {

if (k == k->parent->right) {

// mirror case 3.2.2

k = k->parent;

leftRotate(k);

// mirror case 3.2.1

k->parent->color = 0;

k->parent->parent->color = 1;

rightRotate(k->parent->parent);

if (k == root) {

break;

root->color = 0;

void printHelper(NodePtr root, string indent, bool last) {


41
// print the tree structure on the screen

if (root != TNULL) {

cout<<indent;

if (last) {

cout<<"R----";

indent += " ";

} else {

cout<<"L----";

indent += "| ";

string sColor = root->color?"RED":"BLACK";

cout<<root->data<<"("<<sColor<<")"<<endl;

printHelper(root->left, indent, false);

printHelper(root->right, indent, true);

// cout<<root->left->data<<endl;

public:

RBTree() {

TNULL = new Node;

TNULL->color = 0;

TNULL->left = nullptr;

TNULL->right = nullptr;

root = TNULL;

// Pre-Order traversal
42
// Node->Left Subtree->Right Subtree

void preorder() {

preOrderHelper(this->root);

// In-Order traversal

// Left Subtree -> Node -> Right Subtree

void inorder() {

inOrderHelper(this->root);

// Post-Order traversal

// Left Subtree -> Right Subtree -> Node

void postorder() {

postOrderHelper(this->root);

// search the tree for the key k

// and return the corresponding node

NodePtr searchTree(int k) {

return searchTreeHelper(this->root, k);

// find the node with the minimum key

NodePtr minimum(NodePtr node) {

while (node->left != TNULL) {

node = node->left;

return node;
43
}

// find the node with the maximum key

NodePtr maximum(NodePtr node) {

while (node->right != TNULL) {

node = node->right;

return node;

// find the successor of a given node

NodePtr successor(NodePtr x) {

// if the right subtree is not null,

// the successor is the leftmost node in the

// right subtree

if (x->right != TNULL) {

return minimum(x->right);

// else it is the lowest ancestor of x whose

// left child is also an ancestor of x.

NodePtr y = x->parent;

while (y != TNULL && x == y->right) {

x = y;

y = y->parent;

return y;

44
// find the predecessor of a given node

NodePtr predecessor(NodePtr x) {

// if the left subtree is not null,

// the predecessor is the rightmost node in the

// left subtree

if (x->left != TNULL) {

return maximum(x->left);

NodePtr y = x->parent;

while (y != TNULL && x == y->left) {

x = y;

y = y->parent;

return y;

// rotate left at node x

void leftRotate(NodePtr x) {

NodePtr y = x->right;

x->right = y->left;

if (y->left != TNULL) {

y->left->parent = x;

y->parent = x->parent;

if (x->parent == nullptr) {

this->root = y;

} else if (x == x->parent->left) {
45
x->parent->left = y;

} else {

x->parent->right = y;

y->left = x;

x->parent = y;

// rotate right at node x

void rightRotate(NodePtr x) {

NodePtr y = x->left;

x->left = y->right;

if (y->right != TNULL) {

y->right->parent = x;

y->parent = x->parent;

if (x->parent == nullptr) {

this->root = y;

} else if (x == x->parent->right) {

x->parent->right = y;

} else {

x->parent->left = y;

y->right = x;

x->parent = y;

// insert the key to the tree in its appropriate position

// and fix the tree


46
void insert(int key) {

// Ordinary Binary Search Insertion

NodePtr node = new Node;

node->parent = nullptr;

node->data = key;

node->left = TNULL;

node->right = TNULL;

node->color = 1; // new node must be red

NodePtr y = nullptr;

NodePtr x = this->root;

while (x != TNULL) {

y = x;

if (node->data < x->data) {

x = x->left;

} else {

x = x->right;

// y is parent of x

node->parent = y;

if (y == nullptr) {

root = node;

} else if (node->data < y->data) {

y->left = node;

} else {

y->right = node;
47
}

// if new node is a root node, simply return

if (node->parent == nullptr){

node->color = 0;

return;

// if the grandparent is null, simply return

if (node->parent->parent == nullptr) {

return;

// Fix the tree

fixInsert(node);

NodePtr getRoot(){

return this->root;

// delete the node from the tree

void deleteNode(int data) {

deleteNodeHelper(this->root, data);

// print the tree structure on the screen

void prettyPrint() {

if (root) {
48
printHelper(this->root, "", true);

};

int main() {

RBTree bst;

bst.insert(8);

bst.insert(18);

bst.insert(5);

bst.insert(15);

bst.insert(17);

bst.insert(25);

bst.insert(40);

bst.insert(80);

bst.deleteNode(25);

bst.prettyPrint();

return 0;

OUTPUT:

R----17(BLACK)

L----8(RED)

L----5(BLACK)

R----15(BLACK)

R----40(RED)
49
L----18(BLACK)

R----80(BLACK)

RESULTS:

Thus, the program is implementation and verified in Red-Black Tree in C++ language.

50
EX.NO:6 IMPLEMENTATION OF HEAP

DATE:

AIM:

Write a program to implementation of Heap in C++ language.

PROGRAM:

#include <iostream>

#include <cstdlib>

#include <vector>

#include <iterator>

using namespace std;

/*

* Class Declaration

*/

class Heap

private:

vector <int> heap;

int left(int parent);

int right(int parent);

int parent(int child);

void heapifyup(int index);

void heapifydown(int index);

public:

Heap()

{}

void Insert(int element);

void DeleteMin();

int ExtractMin();
51
void DisplayHeap();

int Size();

};

/*

* Return Heap Size

*/

int Heap::Size()

return heap.size();

/*

* Insert Element into a Heap

*/

void Heap::Insert(int element)

heap.push_back(element);

heapifyup(heap.size() -1);

/*

* Delete Minimum Element

*/

void Heap::DeleteMin()

if (heap.size() == 0)

cout<<"Heap is Empty"<<endl;

return;

}
52
heap[0] = heap.at(heap.size() - 1);

heap.pop_back();

heapifydown(0);

cout<<"Element Deleted"<<endl;

/*

* Extract Minimum Element

*/

int Heap::ExtractMin()

if (heap.size() == 0)

return -1;

else

return heap.front();

/*

* Display Heap

*/

void Heap::DisplayHeap()

vector <int>::iterator pos = heap.begin();

cout<<"Heap --> ";

while (pos != heap.end())

cout<<*pos<<" ";
53
pos++;

cout<<endl;

/*

* Return Left Child

*/

int Heap::left(int parent)

int l = 2 * parent + 1;

if(l < heap.size())

return l;

else

return -1;

/*

* Return Right Child

*/

int Heap::right(int parent)

int r = 2 * parent + 2;

if(r < heap.size())

return r;

else

return -1;

54
/*

* Return Parent

*/

int Heap::parent(int child)

int p = (child - 1)/2;

if(child == 0)

return -1;

else

return p;

/*

* Heapify- Maintain Heap Structure bottom up

*/

void Heap::heapifyup(int in)

if (in >= 0 && parent(in) >= 0 && heap[parent(in)] > heap[in])

int temp = heap[in];

heap[in] = heap[parent(in)];

heap[parent(in)] = temp;

heapifyup(parent(in));

/*

* Heapify- Maintain Heap Structure top down

*/
55
void Heap::heapifydown(int in)

int child = left(in);

int child1 = right(in);

if (child >= 0 && child1 >= 0 && heap[child] > heap[child1])

child = child1;

if (child > 0)

int temp = heap[in];

heap[in] = heap[child];

heap[child] = temp;

heapifydown(child);

/*

* Main Contains Menu

*/

int main()

Heap h;

while (1)

cout<<"------------------"<<endl;

cout<<"Operations on Heap"<<endl;

cout<<"------------------"<<endl;
56
cout<<"1.Insert Element"<<endl;

cout<<"2.Delete Minimum Element"<<endl;

cout<<"3.Extract Minimum Element"<<endl;

cout<<"4.Print Heap"<<endl;

cout<<"5.Exit"<<endl;

int choice, element;

cout<<"Enter your choice: ";

cin>>choice;

switch(choice)

case 1:

cout<<"Enter the element to be inserted: ";

cin>>element;

h.Insert(element);

break;

case 2:

h.DeleteMin();

break;

case 3:

cout<<"Minimum Element: ";

if (h.ExtractMin() == -1)

cout<<"Heap is Empty"<<endl;

else

cout<<"Minimum Element: "<<h.ExtractMin()<<endl;

break;

case 4:

cout<<"Displaying elements of Hwap: ";


57
h.DisplayHeap();

break;

case 5:

exit(1);

default:

cout<<"Enter Correct Choice"<<endl;

return 0;

OUTPUT:

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 7

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element


58
3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 7

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 4

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 4 7

------------------

Operations on Heap

------------------

1.Insert Element
59
2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 9

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 4 7 9

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 3

------------------

Operations on Heap

------------------
60
1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 3 4 9 7

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 3

Minimum Element: Minimum Element: 3

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 5

------------------

Operations on Heap
61
------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 3 4 9 7 5

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 11

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 3 4 9 7 5 11

------------------
62
Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 1

Enter the element to be inserted: 2

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 2 4 3 7 5 11 9

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 2

Element Deleted
63
------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 3 4 11 7 5 9

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 3

Minimum Element: Minimum Element: 3

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 2


64
Element Deleted

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 4

Displaying elements of Hwap: Heap --> 4 5 11 7 9

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit

Enter your choice: 3

Minimum Element: Minimum Element: 4

------------------

Operations on Heap

------------------

1.Insert Element

2.Delete Minimum Element

3.Extract Minimum Element

4.Print Heap

5.Exit
65
Enter your choice: 5

------------------

(program exited with code: 0)

RESULTS:

Thus, the program is implementation and verified in Heap in C++ language.

66
EX.NO:7 IMPLEMENTATION OF FIBONACCI HEAP

DATE:

AIM:

Write a program to implementation of Fibonacci Heap in C++ language.

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

{
67
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();

};

/*

* Initialize Heap

*/

node* FibonacciHeap::InitializeHeap()

node* np;

np = NULL;
68
return np;

/*

* Create Node

*/

node* FibonacciHeap::Create_node(int value)

node* x = new node;

x->n = value;

return x;

/*

* Insert Node

*/

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;
69
if (x->n < H->n)

H = x;

else

H = x;

nH = nH + 1;

return H;

/*

* Link Nodes in Fibonnaci Heap

*/

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)


70
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;

/*

* Display Fibonnaci Heap

*/

int FibonacciHeap::Display(node* H)

node* p = H;

if (p == NULL)

cout<<"The Heap is Empty"<<endl;

return 0;

}
71
cout<<"The root nodes of Heap are: "<<endl;

do

cout<<p->n;

p = p->right;

if (p != H)

cout<<"-->";

while (p != H && p->right != NULL);

cout<<endl;

/*

* Extract Min Node in Fibonnaci Heap

*/

node* FibonacciHeap::Extract_Min(node* H1)

node* p;

node* ptr;

node* z = H1;

p = z;

ptr = z;

if (z == NULL)

return z;

node* x;

node* np;

x = NULL;

if (z->child != NULL)
72
x = z->child;

if (x != NULL)

ptr = x;

do

np = x->right;

(H1->left)->right = x;

x->right = H1;

x->left = H1->left;

H1->left = x;

if (x->n < H1->n)

H1 = x;

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;
73
return p;

/*

* Consolidate Node in Fibonnaci Heap

*/

int FibonacciHeap::Consolidate(node* H1)

int d, i;

float f = (log(nH)) / (log(2));

int D = f;

node* A[D];

for (i = 0; i <= D; i++)

A[i] = NULL;

node* x = H1;

node* y;

node* np;

node* pt = x;

do

pt = pt->right;

d = x->degree;

while (A[d] != NULL)

y = A[d];

if (x->n > y->n)

np = x;

x = y;

y = np;
74
}

if (y == H1)

H1 = x;

Fibonnaci_link(H1, y, x);

if (x->right == x)

H1 = x;

A[d] = NULL;

d = d + 1;

A[d] = x;

x = x->right;

while (x != H1);

H = NULL;

for (int j = 0; j <= D; j++)

if (A[j] != NULL)

A[j]->left = A[j];

A[j]->right =A[j];

if (H != NULL)

(H->left)->right = A[j];

A[j]->right = H;

A[j]->left = H->left;

H->left = A[j];

if (A[j]->n < H->n)

H = A[j];

}
75
else

H = A[j];

if(H == NULL)

H = A[j];

else if (A[j]->n < H->n)

H = A[j];

/*

* Decrease key of Nodes in Fibonnaci Heap

*/

int FibonacciHeap::Decrease_key(node*H1, int x, int k)

node* y;

if (H1 == NULL)

cout<<"The Heap is Empty"<<endl;

return 0;

node* ptr = Find(H1, x);

if (ptr == NULL)

cout<<"Node not found in the Heap"<<endl;

return 1;

}
76
if (ptr->n < k)

cout<<"Entered key greater than current key"<<endl;

return 0;

ptr->n = k;

y = ptr->parent;

if (y != NULL && ptr->n < y->n)

Cut(H1, ptr, y);

Cascase_cut(H1, y);

if (ptr->n < H->n)

H = ptr;

return 0;

/*

* Cut Nodes in Fibonnaci Heap

*/

int FibonacciHeap::Cut(node* H1, node* x, node* y)

if (x == x->right)

y->child = NULL;

(x->left)->right = x->right;

(x->right)->left = x->left;

if (x == y->child)

y->child = x->right;

y->degree = y->degree - 1;

x->right = x;
77
x->left = x;

(H1->left)->right = x;

x->right = H1;

x->left = H1->left;

H1->left = x;

x->parent = NULL;

x->mark = 'F';

/*

* Cascade Cutting in Fibonnaci Heap

*/

int FibonacciHeap::Cascase_cut(node* H1, node* y)

node* z = y->parent;

if (z != NULL)

if (y->mark == 'F')

y->mark = 'T';

else

Cut(H1, y, z);

Cascase_cut(H1, z);

78
/*

* Find Nodes in Fibonnaci Heap

*/

node* FibonacciHeap::Find(node* H, int k)

node* x = H;

x->C = 'Y';

node* p = NULL;

if (x->n == k)

p = x;

x->C = 'N';

return p;

if (p == NULL)

if (x->child != NULL )

p = Find(x->child, k);

if ((x->right)->C != 'Y' )

p = Find(x->right, k);

x->C = 'N';

return p;

/*

* Delete Nodes in Fibonnaci Heap

*/

int FibonacciHeap::Delete_key(node* H1, int k)

{
79
node* np = NULL;

int t;

t = Decrease_key(H1, k, -5000);

if (!t)

np = Extract_Min(H);

if (np != NULL)

cout<<"Key Deleted"<<endl;

else

cout<<"Key not Deleted"<<endl;

return 0;

/*

* Main Contains Menu

*/

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;


80
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: ";


81
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:

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap


82
2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 1

Enter the element to be inserted: 9

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 1

Enter the element to be inserted: 8

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 1

Enter the element to be inserted: 7


83
----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 1

Enter the element to be inserted: 6

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 1

Enter the element to be inserted: 5

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node
84
5)Display Heap

6)Exit

Enter Your Choice: 5

The Heap is:

The root nodes of Heap are:

5-->6-->7-->8-->9

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 2

The node with minimum key: 5

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 3

Enter the key to be decreased: 3

Enter new key value: 1


85
Node not found in the Heap

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 3

Enter the key to be decreased: 5

Enter new key value: 2

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node

3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 2

The node with minimum key: 2

----------------------------

Operations on Binomial heap

----------------------------

1)Insert Element in the heap

2)Extract Minimum key node


86
3)Decrease key of a node

4)Delete a node

5)Display Heap

6)Exit

Enter Your Choice: 6

------------------

RESULTS:

Thus, the program is implementation and verified in Fibonacci Heap in C++ language.

87
EX.NO:8 GRAPH TRAVERSALS

DATE:

AIM:

Write a program to implementation of Graph Traversals in C++ language.

PROGRAM:

Breadth First Search:

#include <iostream>
#include <list>
#include <memory>

class Graph
{
int _V;
bool _directed;
std::unique_ptr< std::list<int> > adj;

public:
Graph(int V, bool directed);
void AddEdge(int v, int w);
void BreadthFirstSearch(int s);
};

Graph::Graph(int V, bool directed) : adj(new std::list<int>[V])


{
_V = V;
_directed = directed;
}

void Graph::AddEdge(int v, int w)


{
std::list<int>* adjacency = adj.get();
adjacency[v].push_back(w);

if (!_directed)
{
adjacency[w].push_back(v);
}
}

void Graph::BreadthFirstSearch(int s)
{
bool *visited = new bool[_V];
for(int i = 0; i < _V; i++)
visited[i] = false;

88
// Create a queue for BFS
std::list<int> queue;

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

// 'i' will be used to get all adjacent vertices of a vertex


std::list<int>::iterator i;

while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
std::cout << s << " ";
queue.pop_front();

// Get all adjacent vertices of the dequeued vertex s


// If a adjacent has not been visited, then mark it visited
// and enqueue it
for(i = (adj.get())[s].begin(); i != (adj.get())[s].end(); ++i)
{
if(!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}

int main()
{
Graph g(7, true);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(0, 3);
g.AddEdge(1, 0);
g.AddEdge(1, 5);
g.AddEdge(2, 5);
g.AddEdge(3, 0);
g.AddEdge(3, 4);
g.AddEdge(4, 6);
g.AddEdge(5, 1);
g.AddEdge(6, 5);

std::cout << "Breadth First Traversal from vertex 2:\n";


g.BreadthFirstSearch(2);

return 0;
}

Depth First Search:

89
#include <iostream>
#include <list>
#include <memory>

class Graph
{
private:
int _V;
bool _directed;
std::unique_ptr< std::list<int> > adj;
void DFSUtil(int v, bool visited[]);

public:
Graph(int V, bool directed);
void AddEdge(int v, int w);
void DepthFirstSearch(int s);
};

Graph::Graph(int V, bool directed) : adj(new std::list<int>[V])


{
_V = V;
_directed = directed;
}

void Graph::AddEdge(int v, int w)


{
std::list<int>* adjacency = adj.get();
adjacency[v].push_back(w);

if (!_directed)
{
adjacency[w].push_back(v);
}
}

void Graph::DFSUtil(int v, bool visited[])


{
// Mark the current node as visited and print it
visited[v] = true;
std::cout << v << " ";

// Recur for all the vertices adjacent to this vertex


std::list<int>::iterator i;
for (i = (adj.get())[v].begin(); i != (adj.get())[v].end(); ++i)
if (!visited[*i])
DFSUtil(*i, visited);
}

// DFS traversal of the vertices reachable from v. It uses recursive DFSUtil()


void Graph::DepthFirstSearch(int v)
{
// Mark all the vertices as not visited

90
std::unique_ptr<bool[]> visited(new bool[_V]);

for (int i = 0; i < _V; i++)


visited[i] = false;

// Call the recursive helper function to print DFS traversal


DFSUtil(v, visited.get());
}

int main()
{
// Create a graph given in the above diagram
Graph g(7, true);
g.AddEdge(0, 1);
g.AddEdge(0, 2);
g.AddEdge(0, 3);
g.AddEdge(1, 0);
g.AddEdge(1, 5);
g.AddEdge(2, 5);
g.AddEdge(3, 0);
g.AddEdge(3, 4);
g.AddEdge(4, 6);
g.AddEdge(5, 1);
g.AddEdge(6, 5);

std::cout << "Depth First Traversal starting from vertex 2:\n";


g.DepthFirstSearch(2);

return 0;
}

OUTPUT:

Breadth First Search:

91
Depth First Search:

RESULTS:

Thus, the program is implementation and verified in Graph Traversals in C++ language.

92
EX.NO:9 IMPLEMENTATION OF SPANNING TREE

DATE:

AIM:

Write a program to implementation of Spanning Tree in C++ language.

PROGRAM:

#include <bits/stdc++.h>

using namespace std;

class Edge{

public:

int src;

int dest;

int wt;

};

bool compare(Edge e1,Edge e2){

return e1.wt<e2.wt;

int getParent(int v,int parent[]){

if(parent[v]==v){

return v;

return getParent(parent[v],parent);

int main()
93
{

int n,E;

cin>>n>>E;

Edge edges[E];

for(int i=0;i<E;i++){

cin>>edges[i].src>>edges[i].dest>>edges[i].wt;

//Kruskal algo

//sorted the edges array in increasing order

sort(edges,edges+E,compare);

Edge output[n-1];

//Union find algorithm to detect cycle

int parent[n];

for(int i=0;i<n;i++){

parent[i]=i;

int count=0;

int i=0;

while(count<n-1){

Edge currentEdge=edges[i];

int p1=getParent(currentEdge.src,parent);

int p2=getParent(currentEdge.dest,parent);

if(p1!=p2){

output[count]=currentEdge;
94
count++;

parent[p1]=p2;

i++;

//Printing the MST

for(int i=0;i<n-1;i++){

if(output[i].src<output[i].dest){

cout<<output[i].src<<" "<<output[i].dest<<" "<<output[i].wt<<endl;

else cout<<output[i].dest<<" "<<output[i].src<<" "<<output[i].wt<<endl;

return 0;

OUTPUT:

Input:
44
013
035

95
121
238

Output:
121
013
035

RESULTS:

Thus, the program is implementation and verified in Spanning Tree in C++ language.

96
EX.NO:10 SHORTEST PATH ALGORITHMS (DIJKSTRA’S ALGORITHM, BELLMAN FORD

DATE: ALGORITHM

AIM:

Write a program to implementation of shortest path algorithms (dijkstra’s algorithm, bellman ford
algorithm in C++ language.

PROGRAM:

DIJKSTRA’S ALGORITHM:

#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++)
{
97
// 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;
}

BELLMAN FORD ALGORITHM:

#include<iostream>
#define MAX 10
using namespace std;

typedef struct edge


{
int src;
int dest;
int wt;
}edge;

void bellman_ford(int nv,edge e[],int src_graph,int ne)


{
int u,v,weight,i,j=0;
int dis[MAX];

/* initializing array 'dis' with 999. 999 denotes infinite distance */


for(i=0;i<nv;i++)
{
dis[i]=999;
}

98
/* distance of source vertex from source vertex is o */
dis[src_graph]=0;

/* relaxing all the edges nv - 1 times */


for(i=0;i<nv-1;i++)
{
for(j=0;j<ne;j++)
{
u=e[j].src;
v=e[j].dest;
weight=e[j].wt;

if(dis[u]!=999 && dis[u]+weight < dis[v])


{
dis[v]=dis[u]+weight;
}
}

/* checking if negative cycle is present */


for(j=0;j<ne;j++)
{
u=e[j].src;
v=e[j].dest;
weight=e[j].wt;

if(dis[u]+weight < dis[v])


{
cout<<"\n\nNEGATIVE CYCLE PRESENT..!!\n";
return;
}
}

cout<<"\nVertex"<<" Distance from source";


for(i=1;i<=nv;i++)
{
cout<<"\n"<<i<<"\t"<<dis[i];
}

int main()
{
int nv,ne,src_graph;
edge e[MAX];

cout<<"Enter the number of vertices: ";


cin>>nv;

99
/* if you enter no of vertices: 5 then vertices will be 1,2,3,4,5. so while giving input enter source and
destination vertex accordingly */
printf("Enter the source vertex of the graph: ");
cin>>src_graph;

cout<<"\nEnter no. of edges: ";


cin>>ne;

for(int i=0;i<ne;i++)
{
cout<<"\nFor edge "<<i+1<<"=>";
cout<<"\nEnter source vertex :";
cin>>e[i].src;
cout<<"Enter destination vertex :";
cin>>e[i].dest;
cout<<"Enter weight :";
cin>>e[i].wt;
}

bellman_ford(nv,e,src_graph,ne);

return 0;
}

OUTPUT:

DIJKSTRA’S ALGORITHM:

Vertex Distance from source

A 0

B 1

C 2

D 4

E 2

F 3

BELLMAN FORD ALGORITHM:

Enter the number of vertices: 4


Enter the source vertex of the graph: 1

Enter no. of edges: 4

For edge 1=>


Enter source vertex :1
Enter destination vertex :2
Enter weight :4

100
For edge 2=>
Enter source vertex :1
Enter destination vertex :3
Enter weight :3

For edge 3=>


Enter source vertex :2
Enter destination vertex :4
Enter weight :7

For edge 4=>


Enter source vertex :3
Enter destination vertex :4
Enter weight :-2

Vertex Distance from source


1 0
2 4
3 3
4 1

RESULTS:

Thus, the program is implementation and verified in shortest path algorithms (dijkstra’s algorithm,
bellman ford algorithm in C++ language.

101
EX.NO:11 IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION

DATE:

AIM:

Write a program to implementation of Matrix chain multiplication in C++ language.

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";
102
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

RESULTS:

Thus, the program is implementation and verified in Matrix chain multiplication in C++ language.

103
EX.NO:12 IMPLEMENTATION OF ACTIVITY SELECTION AND HUFFMAN CODING

DATE:

AIM:

Write a program to implementation of Activity selection and Huffman coding in C++ language.

PROGRAM:

ACTIVITY SELECTION:

#include <bits/stdc++.h>

using namespace std;

struct activity

int start, finish;

};

bool Compare(activity s1, activity s2)

return (s1.finish < s2.finish);

void print(activity vec[], int n)

sort(vec, vec+n, Compare);

cout << "Following activities are selected - ";


104
int i = 0;

cout << "(" << vec[i].start << ", " << vec[i].finish << "), ";

for (int j = 1; j < n; j++)

if (vec[j].start >=vec[i].finish)

cout << "(" << vec[j].start << ", "

<< vec[j].finish << "), ";

i = j;

int main()

activity vec[] = {{4, 8}, {2, 5}, {4, 6}, {1, 4},

{3, 7}, {8, 9}};

int n = sizeof(vec)/sizeof(vec[0]);

print(vec, n);

return 0;

HUFFMAN CODING:
105
#include <bits/stdc++.h>

using namespace std;

// A Huffman tree node

struct MinHeapNode {

// One of the input characters

char data;

// Frequency of the character

unsigned freq;

// Left and right child

MinHeapNode *left, *right;

MinHeapNode(char data, unsigned freq)

left = right = NULL;

this->data = data;

this->freq = freq;

};

struct compare {

bool operator()(MinHeapNode* l, MinHeapNode* r)

return (l->freq > r->freq);

};
106
void printCodes(struct MinHeapNode* root, string str)

if (!root)

return;

if (root->data != '$')

cout << root->data << ": " << str << "\n";

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

printCodes(root->right, str + "1");

void HuffmanCodes(char data[], int freq[], int size)

struct MinHeapNode *left, *right, *top;

priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;

for (int i = 0; i < size; ++i)

minHeap.push(new MinHeapNode(data[i], freq[i]));

while (minHeap.size() != 1) {

left = minHeap.top();

minHeap.pop();

right = minHeap.top();

minHeap.pop();

top = new MinHeapNode('$', left->freq + right->freq);

107
top->left = left;

top->right = right;

minHeap.push(top);

printCodes(minHeap.top(), "");

// Driver program to test above functions

int main()

char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

int freq[] = { 10, 5, 14, 14, 7, 9 };

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

HuffmanCodes(arr, freq, size);

return 0;

OUTPUT:

ACTIVITY SELECTION:

Following activities are selected - (1,4), (4,6), (8,9)

HUFFMAN CODING:

b:000

e:001

c:01

d:10

108
f:111

a:110

RESULTS:

Thus, the program is implementation and verified in Activity selection and Huffman coding in C++
language.

109

You might also like