0% found this document useful (0 votes)
3 views88 pages

CP4161 Advanced Data Structures and Algorithms Laboratory Manual

The document outlines multiple experiments implementing recursive and iterative functions for tree traversal and Fibonacci, as well as sorting algorithms like Merge Sort and Quick Sort. Each section includes aims, algorithms, C++ programs, and results confirming successful execution. Additionally, it describes the implementation of a Binary Search Tree with traversal methods.

Uploaded by

Arun Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views88 pages

CP4161 Advanced Data Structures and Algorithms Laboratory Manual

The document outlines multiple experiments implementing recursive and iterative functions for tree traversal and Fibonacci, as well as sorting algorithms like Merge Sort and Quick Sort. Each section includes aims, algorithms, C++ programs, and results confirming successful execution. Additionally, it describes the implementation of a Binary Search Tree with traversal methods.

Uploaded by

Arun Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Page 1 of 88

Exp No : 1
Implementation of recursive function for tree traversal and Fibonacci
Date :

Aim:
To write a program to implement of Recursive function for tree traversal and Fibonacci
Algorithm:
Input: Read n value
Output: Prints the nth Fibonacci term
1. Step1: Start
2. Step2: Read n value for computing nth term in Fibonacci series
3. Step3: call Fibonacci (n)
4. Step4: Print the nth term
5. Step5: End
6. Fibonacci(n)
7. // Algorithm Fibonacci computes the nth Fibonacci number, for appropriate values of n.
8. Step1: If n = 0 then go to step2 else go to step3
9. Step2: return 0
10. Step3: If n = 1 then go to step4 else go to step5
11. Step4: return 1
12. Step5: return(Fibonacci (n-1) + Fibonacci (n-2))

Page 2 of 88
PROGRAM
#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;
};

//Utility function to create a new tree node


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;

// first recur on left subtree


printPostorder(node->left);

// then recur on right subtree


printPostorder(node->right);

// now deal with the node


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

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


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

Page 3 of 88
/* 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);
}

/* 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 = 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;
}

Page 4 of 88
Output :

gedit e1.cpp
novice@it002:~$ g++ e1.cpp
novice@it002:~$ ./a.out

Preorder traversal of binary tree is


12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231

RESULT:
Thus the C++ program to implement recursive function for tree traversal and Fibonacci was
written, executed and verified successfully.

Page 5 of 88
Exp No : 2
Implementation of iteration function for tree traversal and Fibonacci
Date :

Aim:
To write a program to implement of Iteration function for tree traversal and Fibonacci
Algorithm:
Input: Read n value
Output: Prints the nth Fibonacci term
Step1: Start
Step2: Read n value for computing nth term in Fibonacci series
Step3: call Fibonacci (n)
Step4: Print the nth term
Step5: End Fibonacci(n)
// Algorithm Fibonacci computes the nth Fibonacci number, for appropriate values of n.
Step1: If n = 0 then go to step2 else go to step3
Step2: return 0
Step3: If n = 1 then go to step4 else go to step5
Step4: return 1
Step5: return(Fibonacci (n-1) + Fibonacci (n-2))

Page 6 of 88
PROGRAM :
#include <bits/stdc++.h>
using namespace std;

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

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

// Iterative function to do Preorder traversal of the tree


void preorderIterative(Node* root)
{
if (root == NULL)
return;

stack<Node*> st;

// start from root node (set current node to root node)


Node* curr = root;

// run till stack is not empty or current is


// not NULL
while (!st.empty() || curr != NULL) {
// Print left children while exist
// and keep pushing right into the
// stack.
while (curr != NULL) {
cout << curr->data << " ";

if (curr->right)
st.push(curr->right);

curr = curr->left;
}

// We reach when curr is NULL, so We


// take out a right child from stack
if (st.empty() == false) {
curr = st.top();

Page 7 of 88
st.pop();
}
}
}
// Driver Code
int main()
{
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(40);
root->left->left->left = new Node(70);
root->left->right = new Node(50);
root->right->left = new Node(60);
root->left->left->right = new Node(80);
preorderIterative(root);
return 0;

Page 8 of 88
Output :

novice@it002:~$ g++ ex21.cpp


novice@it002:~$ ./a.out
10 20 40 70 80 50 30 60

RESULT:
Thus the C++ program to implement iteration function for tree traversal and Fibonacci was
written, executed and verified successfully

Page 9 of 88
Exp No : 3a Implementation of Merge Sort and Quick Sort analysis

Date : 3a. Implementation of Merge Sort analysis

AIM:

To write a program to implement merge sort.

ALGORITHM:
1. If the list has only one element, return the list and terminate.
2. Split the list into two halves that are as equal in length as possible
3. Using recursion, sort both lists using merge sort.
4. Merge the two sorted lists and return the result.
5. Stop the program.

Page 10 of 88
PROGRAM
#include<iostream>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int *array, int size) {
for(int i = 0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void merge(int *array, int l, int m, int r) {
int i, j, k, nl, nr;
//size of left and right sub-arrays
nl = m-l+1; nr = r-m;
int larr[nl], rarr[nr];
//fill left and right sub-arrays
for(i = 0; i<nl; i++)
larr[i] = array[l+i];
for(j = 0; j<nr; j++)
rarr[j] = array[m+1+j];
i = 0; j = 0; k = l;
//marge temp arrays to real array
while(i < nl && j<nr) {
if(larr[i] <= rarr[j]) {
array[k] = larr[i];
i++;
}else{
array[k] = rarr[j];
j++;
}
k++;
}
while(i<nl) { //extra element in left array
array[k] = larr[i];
i++; k++;
}
while(j<nr) { //extra element in right array
array[k] = rarr[j];
j++; k++;
}
}
void mergeSort(int *array, int l, int r) {

Page 11 of 88
int m;
if(l < r) {
int m = l+(r-l)/2;
// Sort first and second arrays
mergeSort(array, l, m);
mergeSort(array, m+1, r);
merge(array, l, m, r);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n]; //create an array with given number of elements
cout << "Enter elements:" << endl;
for(int i = 0; i<n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
mergeSort(arr, 0, n-1); //(n-1) for last index
cout << "Array after Sorting: ";
display(arr, n);
}

Page 12 of 88
OUTPUT :

novice@it002:~$ g++ merg.cpp


novice@it002:~$ ./a.out
Enter the number of elements: 5
Enter elements:
33 44 22 88 10
Array before Sorting: 33 44 22 88 10
Array after Sorting: 10 22 33 44 88

RESULT:
Thus the C++ program to Merge Sort was written, executed and verified successfully

Page 13 of 88
Exp No : 3b
Quick Sort
Date :

AIM:

To write a program to implement quick sort.

ALGORTIHM:

1. Choose an element, called pivot, from the list. Generally pivot can be the middle index
element
2. Reorder the list so that all elements with values less than the pivot come before the pivot
3. All elements with values greater than the pivot come after it (equal values can go either
way).
a. After this partitioning, the pivot is in its final position. This is called the partition
operation.
4. Recursively apply the above steps to the sub-list of elements with smaller values and
separately the sub-list of elements with greater values.
5. Stop the Program.

Page 14 of 88
PROGRAM
#include <iostream>
using namespace std;

int partition(int arr[], int start, int end)


{

int pivot = arr[start];

int count = 0;
for (int i = start + 1; i <= end; i++) {
if (arr[i] <= pivot)
count++;
}

// Giving pivot element its correct position


int pivotIndex = start + count;
swap(arr[pivotIndex], arr[start]);

// Sorting left and right parts of the pivot element


int i = start, j = end;

while (i < pivotIndex && j > pivotIndex) {

while (arr[i] <= pivot) {


i++;
}

while (arr[j] > pivot) {


j--;
}

if (i < pivotIndex && j > pivotIndex) {


swap(arr[i++], arr[j--]);
}
}

return pivotIndex;
}

void quickSort(int arr[], int start, int end)


{

// base case
if (start >= end)
return;

Page 15 of 88
// partitioning the array
int p = partition(arr, start, end);

// Sorting the left part


quickSort(arr, start, p - 1);

// Sorting the right part


quickSort(arr, p + 1, end);
}

int main()
{

int arr[] = { 9, 3, 4, 2, 1, 8 };
int n = 6;

quickSort(arr, 0, n - 1);

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


cout << arr[i] << " ";
}

return 0;
}

Page 16 of 88
OUTPUT :

123489

RESULT:
Thus the C++ program to Quick Sort was written, executed and verified successfully

Page 17 of 88
Exp No : 4
IMPLEMENTATION OF BINARY SEARCH TREE
Date :

AIM:
To write a program for implementing Binary Search Tree.

ALGORITHM:

1. Read the search element from the user


2. Compare, the search element with the value of root node in the tree.
3. If both are matching, then display "Given node found!!!" and terminate the function
4. If both are not matching, then check whether search element is smaller or larger than
that node value.
5. If search element is smaller, then continue the search process in left subtree.
6. If search element is larger, then continue the search process in right subtree.
7. Repeat the same until we found exact element or we completed with a leaf node
8. If we reach to the node with search value, then display "Element is found" and
terminate the function.
9. If we reach to a leaf node and it is also not matching, then display "Element not
found" and terminate the function.

Page 18 of 88
PROGRAM
#include <iostream>
using namespace std;
//#include <conio.h>
struct tree
{
tree *l, *r;
int data;
}*root = NULL, *p = NULL, *np = NULL, *q;

void create()
{
int value,c = 0;
while (c < 7)
{
if (root == NULL)
{
root = new tree;
cout<<"enter value of root node\n";
cin>>root->data;
root->r=NULL;
root->l=NULL;
}
else
{
p = root;
cout<<"enter value of node\n";
cin>>value;
while(true)
{
if (value < p->data)
{
if (p->l == NULL)
{
p->l = new tree;
p = p->l;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in left\n";
break;
}
else if (p->l != NULL)
{
p = p->l;

Page 19 of 88
}
}
else if (value > p->data)
{
if (p->r == NULL)
{
p->r = new tree;
p = p->r;
p->data = value;
p->l = NULL;
p->r = NULL;
cout<<"value entered in right\n";
break;
}
else if (p->r != NULL)
{
p = p->r;
}
}
}
}
c++;
}
}
void inorder(tree *p)
{
if (p != NULL)
{
inorder(p->l);
cout<<p->data<<endl;
inorder(p->r);
}
}
void preorder(tree *p)
{
if (p != NULL)
{
cout<<p->data<<endl;
preorder(p->l);
preorder(p->r);
}
}
void postorder(tree *p)
{
if (p != NULL)
{

Page 20 of 88
postorder(p->l);
postorder(p->r);
cout<<p->data<<endl;
}
}
int main()
{
create();
cout<<"printing traversal in inorder\n";
inorder(root);
cout<<"printing traversal in preorder\n";
preorder(root);
cout<<"printing traversal in postorder\n";
postorder(root);
// getch();
}

Page 21 of 88
Output :

./a.out
enter value of root node
7
enter value of node
8
value entered in right
enter value of node
4
value entered in left
enter value of node
6
value entered in right
enter value of node
3
value entered in left
enter value of node
5
value entered in left
enter value of node
2
value entered in left
printing traversal in inorder
2
3
4
5
6
7
8
printing traversal in preorder
7
4
3
2
6
5
8

Page 22 of 88
printing traversal in postorder
2
3
5
6
4
8
7

RESULT:
Thus the C++ program to Binary Search tree was written, executed and verified successfully

Page 23 of 88
Exp No : 5
RED-BLACK TREE IMPLEMENTATION
Date :

AIM:

To write a program to implement Red-Black Tree.

ALGORITHM:

1. Check whether tree is Empty.


2. If tree is Empty then insert the new Node as Root node with color Black and exit
from the operation.
3. If tree is not empty then insert the new Node as a leaf node with Red color.
4. If the parent of new Node is Black then exit from the operation.
5. If the parent of new Node is Red then check the color of parent node's sibling of new
Node.
6. If it is Black or NULL node then make a suitable Rotation and Recolour it.
7. If it is Red coloured node then perform Recolour and Recheck it. Repeat the same
until tree becomes Red Black Tree.

Page 24 of 88
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;

Page 25 of 88
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;

Page 26 of 88
}
}
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)

Page 27 of 88
{
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. ";

Page 28 of 88
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::delfix(node *p)


{
node *s;
while(p!=root&&p->color=='b')
{
if(p->parent->left==p)
{

Page 29 of 88
s=p->parent->right;
if(s->color=='r')
{
s->color='b';
p->parent->color='r';
leftrotate(p->parent);
s=p->parent->right;
}
if(s->right->color=='b'&&s->left->color=='b')
{
s->color='r';
p=p->parent;
}
else
{
if(s->right->color=='b')
{
s->left->color=='b';
s->color='r';
rightrotate(s);
s=p->parent->right;
}
s->color=p->parent->color;
p->parent->color='b';
s->right->color='b';
leftrotate(p->parent);
p=root;
}
}
else
{
s=p->parent->left;
if(s->color=='r')
{
s->color='b';
p->parent->color='r';
rightrotate(p->parent);
s=p->parent->left;
}
if(s->left->color=='b'&&s->right->color=='b')
{
s->color='r';
p=p->parent;
}
else
{

Page 30 of 88
if(s->left->color=='b')
{
s->right->color='b';
s->color='r';
leftrotate(s);
s=p->parent->left;
}
s->color=p->parent->color;
p->parent->color='b';
s->left->color='b';
rightrotate(p->parent);
p=root;
}
}
p->color='b';
root->color='b';
}
}

void RBtree::leftrotate(node *p)


{
if(p->right==NULL)
return ;
else
{
node *y=p->right;
if(y->left!=NULL)
{
p->right=y->left;
y->left->parent=p;
}
else
p->right=NULL;
if(p->parent!=NULL)
y->parent=p->parent;
if(p->parent==NULL)
root=y;
else
{
if(p==p->parent->left)
p->parent->left=y;
else
p->parent->right=y;
}
y->left=p;
p->parent=y;

Page 31 of 88
}
}
void RBtree::rightrotate(node *p)
{
if(p->left==NULL)
return ;
else
{
node *y=p->left;
if(y->right!=NULL)
{
p->left=y->right;
y->right->parent=p;
}
else
p->left=NULL;
if(p->parent!=NULL)
y->parent=p->parent;
if(p->parent==NULL)
root=y;
else
{
if(p==p->parent->left)
p->parent->left=y;
else
p->parent->right=y;
}
y->right=p;
p->parent=y;
}
}

node* RBtree::successor(node *p)


{
node *y=NULL;
if(p->left!=NULL)
{
y=p->left;
while(y->right!=NULL)
y=y->right;
}
else
{
y=p->right;
while(y->left!=NULL)
y=y->left;

Page 32 of 88
}
return y;
}

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

Page 33 of 88
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. ";

Page 34 of 88
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;
}

Page 35 of 88
OUTPUT :

gedit ex5.cpp
novice@it002:~$ g++ ex5.cpp
novice@it002:~$ ./a.out

RED BLACK TREE


1. Insert in the tree
2. Delete a node from the tree
3. Search for an element in the tree
4. Display the tree
5. Exit
Enter Your Choice: 1

Enter key of the node to be inserted: 23

Node Inserted.

RED BLACK TREE


1. Insert in the tree
2. Delete a node from the tree
3. Search for an element in the tree
4. Display the tree
5. Exit
Enter Your Choice: 3

Enter key of the node to be searched: 2

Element Not Found.

RED BLACK TREE


1. Insert in the tree
2. Delete a node from the tree
3. Search for an element in the tree
4. Display the tree
5. Exit
Enter Your Choice: 1

Enter key of the node to be inserted: 34

Node Inserted.

RED BLACK TREE


1. Insert in the tree

Page 36 of 88
2. Delete a node from the tree
3. Search for an element in the tree
4. Display the tree
5. Exit
Enter Your Choice: 4

NODE:
Key: 23
Colour: Black
There is no parent of the node.
Right Child: 34
There is no left child of the node.

Right:

NODE:
Key: 34
Colour: Red
Parent: 23
There is no right child of the node.
There is no left child of the node.

RED BLACK TREE


1. Insert in the tree
2. Delete a node from the tree
3. Search for an element in the tree
4. Display the tree
5. Exit
Enter Your Choice:

RESULT:
Thus the C++ program to Red-Black tree was written, executed and verified successfully

Page 37 of 88
Exp No : 6
HEAP IMPLEMENTATION
Date :

AIM:
To write a program for heap implement

ALGORITHM:
1. Call the buildMaxHeap() function on the list. Also referred to as heapify(), this
builds a heap from a list in O(n) operations.
2. Swap the first element of the list with the final element. Decrease the considered
range of the list by one.
3. Call the siftDown() function on the list to sift the new first element to its
appropriate index in the heap.
4. Go to step (2) unless the considered range of the list is one element.
5. The buildMaxHeap() operation is run once, and is O(n) in performance. The
siftDown() function is O(log n), and is called n times. Therefore, the performance
of this algorithm is O(n + n log n) = O(n log n).

Page 38 of 88
PROGRAM
#include <iostream>
#include <vector>
using namespace std;

// uses a vector to creat a Binar Heap


class BinHeap{

private:
vector<int> heapvector;
int currentSize;

public:
// initializes the vector and an attribute currentSize
// as 0 to allow for interger division.
BinHeap(vector<int> heapvector){
this->heapvector = heapvector;
this->currentSize = 0;
}

// prelocates and item as far up in the


// tree as possible to maintain
// the Heap property
void percUp(int i){
while ((i / 2) > 0){
if (this->heapvector[i] < this->heapvector[i/2]){
int tmp = this->heapvector[i/2];
this->heapvector[i/2] = this->heapvector[i];
this->heapvector[i] = tmp;
}
i = i/2;
}

// appends item to the end of the vector


void insert(int k){
this->heapvector.push_back(k);
this->currentSize = this->currentSize + 1;
this->percUp(this->currentSize);
}

// prelocates and item as far up in the


// tree as possible to maintain
// the Heap property
void percDown(int i){

Page 39 of 88
while ((i*2) <= this->currentSize){
int mc = this->minChild(i);
if (this->heapvector[i] > this->heapvector[mc]){
int tmp = this->heapvector[i];
this->heapvector[i] = this->heapvector[mc];
this->heapvector[mc] = tmp;
}
i = mc;
}
}

int minChild(int i){


if (((i*2)+1) > this->currentSize){
return i * 2;
}
else{
if (this->heapvector[i*2] < this->heapvector[(i*2)+1]){
return i * 2;
}
else{
return (i * 2) + 1;
}
}
}

// restores full complince with the heap structure


// and heap order properties after the root is removed
// by taking the last item and moving it to the root position
// and pushing the new root node down the tree to its proper postion.
int delMin(){
int retval = this->heapvector[1];
this->heapvector[1] = this->heapvector[this->currentSize];
this->currentSize = this->currentSize - 1;
this->heapvector.pop_back();
this->percDown(1);
return retval;
}

void buildheap(vector<int> avector){


int i = avector.size() / 2;
this->currentSize = avector.size();
this->heapvector.insert(this->heapvector.end(), avector.begin(), avector.end());
while (i > 0){
this->percDown(i);
i = i - 1;
}

Page 40 of 88
}

bool isEmpty(){
if (this->heapvector.size()>0){
return false;
}
return true;
}

int findMin(){
return this->heapvector[1];
}
};
int main(){
int arr[] = {9, 5, 6, 2, 3};
vector<int> a(arr,arr+(sizeof(arr)/ sizeof(arr[0])));

vector<int> vec;
vec.push_back(0);

BinHeap *bh = new BinHeap(vec);


bh->buildheap(a);

cout << bh->delMin() << endl;


cout << bh->delMin() << endl;
cout << bh->delMin() << endl;
cout << bh->delMin() << endl;
cout << bh->delMin() << endl;
return 0;
}

Page 41 of 88
OUTPUT :

g++ ex6.cpp
novice@it002:~$ ./a.out
2
3
5
6
9

RESULT:
Thus the C++ program to Heap tree was written, executed and verified successfully

Page 42 of 88
Exp No : 7
FIBONACCI HEAP IMPLEMENTATION
Date :

AIM:
To write a program for Fibonacci heap implement.

ALGORITHM:
1. Call the buildMinHeap() function on the list.
2. insert(x) inserts a node x into the heap.
3. minimum() returns the node in the heap with minimum key.
4. extractMin() deletes the node with minimum key from the heap.
5. union(H) merge heap H and create a new one.
6. decreaseKey(x,k) assigns to node x within the heap the new key value k, which is
assumed to be no greater than its current key value.
7. delete(x) deletes node x from the heap.

Page 43 of 88
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();
}
};

Page 44 of 88
/*
* Initialize Heap
*/
node* FibonacciHeap::InitializeHeap()
{
node* np;
np = NULL;
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;
if (x->n < H->n)
H = x;
}
else
{
H = x;
}
nH = nH + 1;
return H;
}

Page 45 of 88
/*
* 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)
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;

Page 46 of 88
return 0;
}
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)
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;

Page 47 of 88
}
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 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;
}
if (y == H1)
H1 = x;

Page 48 of 88
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];
}
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)
{

Page 49 of 88
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;
}
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;
x->left = x;
(H1->left)->right = x;
x->right = H1;
x->left = H1->left;
H1->left = x;
x->parent = NULL;
x->mark = 'F';
}

Page 50 of 88
/*
* 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);
}
}
}

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

Page 51 of 88
* Delete Nodes in Fibonnaci Heap
*/
int FibonacciHeap::Delete_key(node* H1, int k)
{
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;
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;

Page 52 of 88
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;
}

Page 53 of 88
OUTPUT :

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

Page 54 of 88
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
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

Page 55 of 88
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
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
3)Decrease key of a node
4)Delete a node
5)Display Heap
6)Exit
Enter Your Choice: 6

Page 56 of 88
RESULT:
Thus the C++ program to Fibonacci Heap tree was written, executed and verified successfully

Page 57 of 88
Exp No : 8
GRAPH TRAVERSALS
Date :

AIM:
To write a program to implement Graph Traversals using Depth First Search tree algorithm.

ALGORITHM:
1. Start at some node, and is now our current node.
2. State that our current node is ‘visited’.
3. Now look at all nodes adjacent to our current node.
4. If we see an adjacent node that has not been ‘visited’, add it to the stack.
5. Then pop of the top node on the stack and traverse to it.
6. And go back to step 1.

Page 58 of 88
PROGRAM
#include <bits/stdc++.h>
using namespace std;
// Graph class represents a directed graph
// using adjacency list representation
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;
// function to add an edge to graph
void addEdge(int v, int w);
// DFS traversal of the vertices
// reachable from v
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)
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";
// Recur for all the vertices adjacent
// to this vertex

Page 59 of 88
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFS(*i);
}
// Driver code
int main()
{
// Create a graph given in the above diagram
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;
}

Page 60 of 88
OUTPUT :

g++ ex8.cpp
novice@it002:~$ ./a.out
Following is Depth First Traversal (starting from vertex 2)
2013

Page 61 of 88
Graph Traversals 8a.
#include<iostream>
#include <list>
using namespace std;
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// Pointer to an array containing adjacency
// lists
list<int> *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{

Page 62 of 88
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// 'i' will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
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[s].begin(); i != adj[s].end(); ++i)

Page 63 of 88
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);

return 0;
}

Page 64 of 88
OUTPUT :
novice@it002:~$ g++ bfs.cpp
novice@it002:~$ ./a.out
Following is Breadth First Traversal (starting from vertex 2)
2031

RESULT:
Thus the C++ program to Graph Traversels tree was written, executed and verified successfully

Page 65 of 88
9a. SPANNING TREE IMPLEMENTATION(KRUSKAL’S)

AIM:
To write a program to implement Spanning tree implementation using kruskal’s algorithm.

ALGORITHM:
1. Create a graph F (a set of trees), where each vertex in the graph is a separate tree.
2. Step:create a set S containing all the edges in the graph.
3. While S is nonempty and F is not yet spanning.
3.1. Remove an edge with minimum weight from S.
4. `3.2. If the removed edge connects two different trees then add it to the forest F,
4.1.1. combining two trees into a single tree.

Page 66 of 88
9b SPANNING TREE IMPLEMENTATION(PRIM’S)

AIM:
To write a program to implement Spanning tree implementation using Prim’s algorithm.
ALGORITHM:
1. Create a set mstSet that keeps track of vertices already included in MST.
2. Assign a key value to all vertices in the input graph. Initialize all key values as
INFINITE.
2.1. Assign key value as 0 for the first vertex so that it is picked first.
3. While mstSet doesn’t include all vertices
3.1. Pick a vertex u which is not there in mstSet and has minimum key value.
3.2. Include u to mstSet.
3.3. Update key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is
less than the previous key value of v, update the key value as weight of u-v.

Page 67 of 88
PROGRAM
#include <iostream>
//#include <conio.h>
using namespace std;
struct node
{
int fr, to, cost;
}p[6];
int c = 0, temp1 = 0, temp = 0;
void prims(int *a, int b[][7], int i, int j)
{
a[i] = 1;
while (c < 6)
{
int min = 999;
for (int i = 0; i < 7; i++)
{
if (a[i] == 1)
{
for (int j = 0; j < 7; )
{
if (b[i][j] >= min || b[i][j] == 0)
{
j++;
}
else if (b[i][j] < min)
{
min = b[i][j];
temp = i;
temp1 = j;
}
}
}
}
a[temp1] = 1;
p[c].fr = temp;
p[c].to = temp1;
p[c].cost = min;
c++;
b[temp][temp1] = b[temp1][temp]=1000;
}
for (int k = 0; k < 6; k++)
{
cout<<"source node:"<<p[k].fr<<endl;
cout<<"destination node:"<<p[k].to<<endl;
cout<<"weight of node"<<p[k].cost<<endl;

Page 68 of 88
}
}
int main()
{
int a[7];
for (int i = 0; i < 7; i++)
{
a[i] = 0;
}
int b[7][7];
for (int i = 0; i < 7; i++)
{
cout<<"enter values for "<<(i+1)<<" row"<<endl;
for (int j = 0; j < 7; j++)
{
cin>>b[i][j];
}
}
prims(a, b, 0, 0);
// getch();
}

Page 69 of 88
OUTPUT :

gedit span.cpp
novice@it002:~$ g++ span.cpp
novice@it002:~$ ./a.out
enter values for 1 row
2 040
3
4
6

534
0
enter values for 2 row
4
5
0
0
3
0
0
enter values for 3 row
3
5
1
2
1
0
0
enter values for 4 row
2
1
3
17
8
1
0
enter values for 5 row
0
0
4
2
0
1
0
enter values for 6 row

Page 70 of 88
0
0
2
2
0
1
0
enter values for 7 row
4
0
4
0
1
1
1
source node:0
destination node:0
weight of node2
source node:0
destination node:2
weight of node3
source node:2
destination node:2
weight of node1
source node:2
destination node:4
weight of node1
source node:4
destination node:5
weight of node1
source node:5
destination node:5
weight of node1

RESULT:
Thus the C++ program Spanning tree implementation using prim s algorithm was written,
executed and verified successfully.

Page 71 of 88
10a.Shortest Path Algorithms( DIJKSTRAS ALGORITHM)
AIM:
To write a C++ program to implement Dijkstra Algorithm.

ALGORITHM:
1. Initialization of all nodes with distance "infinite"; initialization of the starting node
with 0.
2. Marking of the distance of the starting node as permanent, all other distances as
temporarily.
3. Setting of starting node as active.Calculation of the temporary distances of all
neighbour nodes of the active node by summing up its distance with the weights of
the edges.
4. If such a calculated distance of a node is smaller as the current one, update the
distance and set the current node as antecessor.
5. This step is also called update and is Dijkstra's central idea.
6. Setting of the node with the minimal temporary distance as active.
7. Mark its distance as permanent.Repeating of steps 4 to 7 until there aren't any nodes
left with a permanent distance, which neighbours still have temporary distance

Page 72 of 88
PROGRAM
#include<iostream>
#include<stdio.h>
using namespace std;
#define INFINITY 9999
#define max 5
void dijkstra(int G[max][max],int n,int startnode);
int main() {
int G[max][max]={{0,1,0,3,10},{1,0,5,0,0},{0,5,0,2,1},{3,0,2,0,6},{10,0,1,6,0}};
int n=5;
int u=0;
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[max][max],int n,int startnode) {
int cost[max][max],distance[max],pred[max];
int visited[max],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++) {
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1) {
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i]) {
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i]) {
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;

Page 73 of 88
}
for(i=0;i<n;i++)
if(i!=startnode) {
cout<<"\nDistance of node"<<i<<"="<<distance[i];
cout<<"\nPath="<<i;
j=i;
do {
j=pred[j];
cout<<"<-"<<j;
}while(j!=startnode);
}
}

Page 74 of 88
OUTPUT :

gedit short1.cpp
novice@it002:~$ g++ short1.cpp
novice@it002:~$ ./a.out

Distance of node1=1
Path=1<-0
Distance of node2=5
Path=2<-3<-0
Distance of node3=3
Path=3<-0
Distance of node4=6
Path=4<-2<-3<-0

RESULT:
Thus the C++ program Shortest Path Algorithm implementation using DIJKSTRAS algorithm
was written, executed and verified successfully.

Page 75 of 88
10b. Shortest Path Algorithms (BELLMANFORD ALGORITHM)

AIM:
To write a C++ program to implement quick sort.

ALGORITHM:
1. Start with the weighted graph
2. Choose the starting vertex and assign infinity path values to all other vertex
3. Visit each edge and relax the path distance if they are inaccurate
4. We need to do this V times because in the worst case the vertex path length might
need to be readjusted V times
5. Notice how the vertex at the top right corner had its path length adjusted
6. After all vertices have their path lengths we check if a negative cycle is present

Page 76 of 88
10: Shortest Path Algorithms - Bellman Ford Algorithm
PROGRAM
#include<iostream>
#include<stdio.h>
#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;
}

/* 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++)
{

Page 77 of 88
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;

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

Page 78 of 88
return 0;
}

Page 79 of 88
OUTPUT :

gedit short2.cpp
novice@it002:~$ g++ short2.cpp
novice@it002:~$ ./a.out
Enter the number of vertices: 3
Enter the source vertex of the graph: 1

Enter no. of edges: 3

For edge 1=>


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

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

Vertex Distance from source


1 0
2 3
3 3

RESULT:
Thus the C++ program Shortest Path Algorithm implementation using BELLMANFORD
algorithm was written, executed and verified successfully.

Page 80 of 88
11. IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION

AIM:
To write a C++ program to implement Matrix Chain Multiplication.

ALGORITHM:
1. A chain of matrices to be multiplied is given as input.
2. For a sequence A1,A2,A3,A4 of 4 matrices, there are 5 different orderings=5
different parethesization.
i) (A1,(A2(A3 A4)))
ii) (A1((A2 A3)A4))
iii) ((A1 A2)(A3 A4))
iv) ((A1(A2 A3))A4)
v) (((A1 A2)A3)A4)Matrix_Multiply(A,B)
3. If coloumns[A]!=rows[B]
i) Then error “incomplete dimensions”
ii) Else for i <- 1 to rows[A]
iii) Do for j <- 1 to columns[B]
 Do c[I,j] <- 0
a. For k<- 1 to columns[A]
b. Do c[i,j]=C[i,j]+A[i,k]+B[i,j]
c. Return c
4. A parenthesizing of the chain of the matrices is obtained as output.

Page 81 of 88
11: Implementation of Matrix Chain Multiplication
PROGRAM
#include<bits/stdc++.h>
using namespace std;
#define INF 1000000009
int min_operation(vector<int> &v, int n)
{
int dp[n+1][n+1];
memset(dp,INF,sizeof(dp));
/*if i=j then dp[i,j]=0.*/
for(int i=1;i<n;i++)
{
dp[i][i]=0;
}
/*Find M[i,j] using the formula.*/
int ran;
for(int i=2;i<n;i++)
{
for(int j=1;j<n-i+1;j++)
{
ran=i+j-1;
for(int k=j;k<=ran-1;k++)
{
/*formula used here.*/
dp[j][ran]=min(dp[j][ran],dp[j][k]+dp[k+1][ran]+v[j-1]*v[k]*v[ran]);
}
}
}
/*return the answer.*/
return dp[1][n-1];
}
int main()
{
/*input values.*/
int n;
/*number of matrices.*/
cin>>n;
/*sequence/chain of the matrices if there are n matrices then chain contain n+1 numbers.*/
vector<int> chain;
for(int i=0;i<n+1;i++)
{
int x;
cin>>x;
chain.push_back(x);

Page 82 of 88
/*store the min operation needed to multiply all the given matrices in ans.*/
int ans=min_operation(chain,n+1);
/*print the result.*/

cout<<ans<<endl;

return 0;
}

Page 83 of 88
OUTPUT :

novice@it002:~$ ./a.out
6
44
5
3
22
5
8
6
2004

RESULT:
Thus the C++ program Matrix Chain Multiplication implementation was written, executed and
verified successfully.

Page 84 of 88
12 IMPLEMENTATION OF ACTIVITY SELECTION & HUFFMAN CODING

AIM:
To write a C++ program to implement Huffman Coding

ALGORITHM:
1. 1.Sort the message ensemble by decreasing probability.
2. N is the cardinal of the message ensemble (number of different messages).
3. 3.Compute the integer n_0 such as 2<=n_0<=D and (N-n_0)/(D-1) is integer.
4. Select the n_0 least probable messages, and assign them each a digit code.
5. 5. Substitute the selected messages by a composite message summing their probability,
and re-order it.
6. 6.While there remains more than one message, do steps thru 8.
7. Select D least probable messages, and assign them each a digit code.
8. Substitute the selected messages by a composite message summing their probability, and
re-order it.
9. The code of each message is given by the concatenation of the code digits of the
aggregate they've been put in.

Page 85 of 88
12: Activity Selection and Huffman Coding

#include <bits/stdc++.h>

using namespace std;


#define N 6 // defines the number of activities

// Structure represents an activity having start time and finish time.


struct Activity
{
int start, finish;
};

// This function is used for sorting activities according to finish time


bool Sort_activity(Activity s1, Activity s2)
{
return (s1.finish< s2.finish);
}

/* Prints maximum number of activities that can


be done by a single person or single machine at a time.
*/
void print_Max_Activities(Activity arr[], int n)
{
// Sort activities according to finish time
sort(arr, arr+n, Sort_activity);

cout<< "Following activities are selected \n";

// Select the first activity


int i = 0;
cout<< "(" <<arr[i].start<< ", " <<arr[i].finish << ")\n";

// Consider the remaining activities from 1 to n-1


for (int j = 1; j < n; j++)
{
// Select this activity if it has start time greater than or equal
// to the finish time of previously selected activity
if (arr[j].start>= arr[i].finish)
{
cout<< "(" <<arr[j].start<< ", "<<arr[j].finish << ") \n";
i = j;
}
}
}

Page 86 of 88
// Driver program
int main()
{
Activity arr[N];
for(int i=0; i<=N-1; i++)
{
cout<<"Enter the start and end time of "<<i+1<<" activity \n";
cin>>arr[i].start>>arr[i].finish;
}

print_Max_Activities(arr, N);
return 0;
}

Page 87 of 88
Output :

gedit ex12.cpp
novice@it002:~$ g++ ex12.cpp
novice@it002:~$ ./a.out
Enter the start and end time of 1 activity
56
Enter the start and end time of 2 activity
12
Enter the start and end time of 3 activity
34
Enter the start and end time of 4 activity
05
Enter the start and end time of 5 activity
56
Enter the start and end time of 6 activity
57
Following activities are selected
(1, 2)
(3, 4)
(5, 6)

RESULT:
Thus the C++ program Activity Selection & Huffman Coding implementation was written,
executed and verified successfully.

Page 88 of 88

You might also like