DATA STRUCTURES LAB MANUAL
DATA STRUCTURES LAB MANUAL
AIM:
To write a program to implement of Recursive function for tree traversal and Fibonacci
ALGORITHM:
1. Start
2. Read n value for computing nth term in Fibonacci series
3. call Fibonacci (n)
4. Print the nth
5. If n = 0 then go to step2 else go to step3
6. return 0
7. If n = 1 then go to step4 else go to step5
8. return 1
9. return(Fibonacci (n-1) + Fibonacci (n-2))
10. End
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);
OUTPUT :
gedit e1.cpp
novice@it002:~$ g++ e1.cpp
novice@it002:~$ ./a.out
RESULT:
Thus the C++ program to implement recursive function for tree traversal and Fibonacci was
written, executed and verified successfully
Ex. No : 2 ITERATION FUNCTION FOR TREE TRAVERSAL AND
Date : FIBONACCI
AIM:
To write a program to implement of Iteration function for tree traversal and Fibonacci
ALGORITHM:
1: Start
2: Read n value for computing nth term in Fibonacci series
3: call Fibonacci (n)
4: Print the nth
5: End Fibonacci(n)
6: If n = 0 then go to step2 else go to step3
7: return 0
8: If n = 1 then go to step4 else go to step5
9: return 1
10: return(Fibonacci (n-1) + Fibonacci (n-2))
PROGRAM :
#include <bits/stdc++.h>
using namespace std;
Node(int data)
{ this->data = data; this-
>left = this->right = NULL;
}
};
stack<Node*> st;
// start from root node (set current node to root node)
Node* curr = root;
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();
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;
OUTPUT :
RESULT:
Thus the C++ program to implement iteration function for tree traversal and Fibonacci was
written, executed and verified successfully
Ex. No : 3a
MERGE SORT
Date :
A IM:
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.
PROGRAM
OUTPUT :
RESULT:
Thus the C++ program to Merge Sort was written, executed and verified successfully.
Ex. No : 3b
QUICK SORT
Date :
AIM:
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.
PROGRAM
#include <iostream>
using namespace std;
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;
return pivotIndex;
}
// base case
if (start >= end)
return;
int main() {
int arr[] = { 9, 3, 4, 2, 1, 8 };
int n = 6;
quickSort(arr, 0, n - 1);
return
0; }
OUTPUT :
123489
RESULT:
Thus the C++ program to Quick Sort was written, executed and verified successfully
Ex No : 4
BINARY SEARCH TREE
Date :
AIM:
To write a program for implementing Binary Search Tree.
ALGORITHM:
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;
}
}
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)
{ 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();
}
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
658
printing traversal in
postorder
2
3
5
RESULT:
Thus the C++ program to Binary Search tree was written, executed and verified Successfully.
Ex. No : 5
RED - BLACK TREE
Date :
AIM:
ALGORITHM:
{ t->parent>color='b';
u-
>color='b'; g-
>color='r'; t=g;
}
} else
{ if(t->parent-
>left==t)
{ t=t-
>parent; rightrotate(t);
} t>parent->color='b';
g-
>color='r'; leftrotate(g);
}
} root-
>color='b';
}
}
void RBtree::del() {
if(root==NULL)
{
cout<<"\nEmpty
Tree." ; return ; }
int x;
cout<<"\nEnter the key of the node to be deleted: ";
cin>>x; node
*p;
p=root; node
*y=NULL; node
*q=NULL;
int found=0;
while(p!=NULL&&found==0)
{ if(p-
>key==x) found=1;
if(found==0)
{ if(p>key<x
) p=p-
>right; else
p=p-
>left;
}
}
if(found==0)
{
cout<<"\nElement Not Found.";
return ; }
else
{
cout<<"\nDeleted Element: "<<p->key; cout<<"\
nColour: "; if(p-
>color=='b')
cout<<"Black\n";
else
cout<<"Red\n";
if(p->parent!=NULL) cout<<"\
nParent: "<<p->parent->key;
else cout<<"\nThere is no parent of
the node. ";
if(p->right!=NULL) cout<<"\nRight Child:
"<<p->right->key; else cout<<"\nThere is no right child
of the node. "; if(p->left!
=NULL)
cout<<"\nLeft Child: "<<p->left->key;
else
cout<<"\nThere is no left child of the node. ";
cout<<"\nNode Deleted."; if(p->left==NULL||p-
>right==NULL)
y=p; else
y=successor(p); if(y->left!
=NULL) q=y->left;
else
{
if(y->right!=NULL)
q=y->right; else
q=NULL;
}
if(q!=NULL) q>parent=y-
>parent; if(y->parent==NULL)
root=q;
else
{
if(y==y->parent->left) y->parent-
>left=q; else
y->parent->right=q;
} if(y!
=p)
{
p->color=y->color;
p->key=y->key;
} if(y>color=='b')
delfix(q);
}
}
{ s>color='r';
p=p->parent;
}
else {
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::disp()
{
display(root);
}
void RBtree::display(node *p)
{
if(root==NULL)
{ cout<<"\nEmpty
Tree.";
return ;
}
if(p!=NULL)
{
cout<<"\n\t NODE: ";
cout<<"\n Key: "<<p->key; cout<<"\n
Colour: "; if(p->color=='b')
cout<<"Black"; else
cout<<"Red"; if(p-
>parent!=NULL)
cout<<"\n Parent: "<<p->parent->key;
else
cout<<"\n There is no parent of the node. ";
if(p->right!=NULL) cout<<"\n Right Child:
"<<p->right->key; else cout<<"\n There
is no right child of the node. "; if(p->left!
=NULL) cout<<"\n Left Child: "<<p->left-
>key; else cout<<"\n There is no left
child of the node. ";
cout<<endl; if(p->left) {
cout<<"\n\nLeft:\n"; display(p>left);
}
/*else
cout<<"\nNo Left Child.\n";*/
if(p->right)
{
cout<<"\n\nRight:\n";
display(p->right);
}
/*else
cout<<"\nNo Right Child.\n"*/
}
}
void RBtree::search()
{
if(root==NULL)
{
cout<<"\nEmpty Tree\n" ;
return ;
}
int x;
cout<<"\n Enter key of the node to be searched:
"; cin>>x; node *p=root;
int found=0;
while(p!=NULL&& found==0)
{ if(p-
>key==x) found=1;
if(found==0)
{ if(p>key<x)
p=p->right;
else p=p-
>left;
}
}
if(found==0) cout<<"\
nElement Not Found.";
else
{
cout<<"\n\t FOUND NODE: ";
cout<<"\n Key: "<<p->key; cout<<"\
n Colour: "; if(p->color=='b')
cout<<"Black"; else cout<<"Red";
if(p->parent!=NULL) cout<<"\n Parent: "<<p->parent-
>key; else cout<<"\n There is no parent of the
node. "; if(p-
>right!=NULL)
cout<<"\n Right Child: "<<p->right->key;
else cout<<"\n There is no right child of the
node. "; if(p->left!=NULL) cout<<"\
n Left Child: "<<p->left->key; else
cout<<"\n There is no left child of the node. ";
cout<<endl;
}
} int main()
{ int ch,y=0;
RBtree obj; do
{ cout<<"\n\t RED BLACK TREE " ;
cout<<"\n 1. Insert in the tree "; cout<<"\n 2.
Delete a node from the tree"; cout<<"\n 3.
Search for an element in the tree"; cout<<"\n 4.
Display the tree "; cout<<"\n 5. Exit " ;
cout<<"\nEnter Your Choice: ";
cin>>ch;
switch(ch) {
case 1 : obj.insert(); cout<<"\
nNode Inserted.\n";
break;
case 2 : obj.del();
break; case 3 :
obj.search();
break; case 4 :
obj.disp(); break;
case 5 : y=1;
break; default : cout<<"\
nEnter a Valid Choice.";
}
cout<<endl; }while( y!
=1); return 1;
}
OUTPUT :
gedit ex5.cpp novice@it002:~$ g+
+ ex5.cpp
novice@it002:~$ ./a.out
Node Inserted.
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: 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.
RESULT:
Thus the C++ program to Red-Black tree was written, executed and verified successfully
Ex No : 6
HEAP
Date :
AIM:
To write programs 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).
PROGRAM
#include <iostream> #include
<vector> using
namespace std;
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;
}
vector<int> vec;
vec.push_back(0);
BinHeap *bh = new BinHeap(vec); bh-
>buildheap(a);
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
Ex. No : 7
FIBONACCI HEAP
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.
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();
}
}; /
*
* 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; }
/*
* 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;
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;
} 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;
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) {
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';
}
/*
* 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; }
/*
* 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; case 2: p
= fh.Extract_Min(H);
if (p != NULL) cout<<"The node
with minimum key: "<<p->n<<endl; else
cout<<"Heap is empty"<<endl; break; case 3:
cout<<"Enter the key to be decreased: ";
cin>>m; cout<<"Enter
new key value: ";
cin>>l; fh.Decrease_key(H,
m, l); break; case 4:
cout<<"Enter the key to be deleted: ";
cin>>m;
fh.Delete_key(H, m);
break;
case 5:
cout<<"The Heap is: "<<endl;
fh.Display(H);
break; case 6:
exit(1); default:
cout<<"Wrong Choice"<<endl;
}
} return 0;
}
OUTPUT :
----------------------------
Operations on Binomial heap
----------------------------
1) Insert Element in the
heap
2)Extract Minimum key node
3)Decrease key of a node
4)Delete
Display Heap
a node 5)
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
Display a node 5)
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
Display a node 5)
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
Display a node 5)
Heap Exit
6)
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
Display a node 5)
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
Display a node 5)
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
Display a node 5)
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
Decrease keyMinimum
of a node
keyDisplay
node 3)Heap
6)Exit a node 5)
4)Delete
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
Display a node 5)
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
Display a node 5)
Heap
6)Exit
Enter Your Choice: 2
The node with minimum key: 2
----------------------------
Operations on Binomial heap
---------------------------- 1)Insert
Element in the heap
RESULT:
Thus the C++ program to Fibonacci Heap tree was written, executed and verified successfully
Ex. No : 8 a
GRAPH TRAVERSALS - DFS
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.
PROGRAM
namespace std;
Graph::addEdge(int v, int w)
list.
} void Graph::DFS(int
v)
// print it
// to this vertex
list<int>::iterator i; for (i = adj[v].begin();
main()
Graph g;
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
vertex 2) \n";
g.DFS(2);
return 0;
OUTPUT :
g++ ex8.cpp novice@it002:~$
./a.out
2013
RESULT:
Thus the C++ program to Graph Traversals Depth First Search tree algorithm was executed
and verified successfully
Ex. No : 8 b
GRAPH TRAVERSALS -BFS
Date :
AIM:
To write a program to implement Graph Traversals using Breath 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.
. PROGRAM
#include<iostream>
namespace std;
// lists
list<int> *adj;
public:
v, int
w)
list<int> queue;
list<int>::iterator i; while(!
queue.empty())
queue.pop_front();
{ if (!
visited[*i])
{ visited[*i] = true;
queue.push_back(*i);
}
}
main()
{
Graph g(4);
g.addEdge(0, 1);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
vertex 2) \n";
g.BFS(2);
return 0;
OUTPUT :
novice@it002:~$ g++ bfs.cpp novice@it002:~$
./a.out
2031
RESULT:
Thus the C++ program to Graph Traversals tree –BFS was executed and verified successfully
Ex. No : 9
SPANNING TREE - PRIM’S
Date :
AIM:
To write a program to implement Spanning tree 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.
a.Assign key value as 0 for the first vertex so that it is picked first.
3. While mstSet doesn’t include all vertices
a. Pick a vertex u which is not there in mstSet and has minimum key value. b.Include
u to mstSet.
c. 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.
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; }
} 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();
}
OUTPUT :
gedit span.cpp
novice@it002:~$ g++
span.cpp novice@it002:~$
./a.out enter values for 1 row 2
040
3
4
6
AIM:
To write a C++ program to implement Shortest Path Algorithm using 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 neighbor
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 neighbors still have temporary distance
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++;
} 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);
}
}
OUTPUT :
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 using Dijkstras algorithm was written, executed and
verified successfully.
Ex. No : 10 b
Date : SHORTEST PATH ALGORITHM - BELLMANFORD ALGORITHM
.
AIM:
To write a C++ program to implement Shortest Path Algorithm using Bellman ford Algorithm.
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
PROGRAM :
#include<iostream>
#include<stdio.h>
#define MAX 10 using
namespace std;
typedef struct edge
{ int
src; int
dest;
int
wt; }edg
e;
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]=99
9;
}
{ u=e[j].sr
c;
v=e[j].dest;
weight=e[j].wt;
{ u=e[j].sr
c;
v=e[j].dest;
weight=e[j].wt;
/* 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;
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 :
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
RESULT:
Thus the C++ program Shortest Path Algorithm using Bellman ford algorithm was written,
executed and verified successfully.
Ex. No : 11
Date : MATRIX CHAIN MULTIPLICATION
.
AIM:
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.
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);
}
/*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;
}
OUTPUT :
novice@it002:~$ ./a.out
6 44
5
3
22
5
8
6
2004
RESULT:
Thus the C++ program Matrix Chain Multiplication was written, executed and verified successfully.
Ex. No : 12
ACTIVITY SELECTION AND HUFFMAN CODING
Date :
AIM:
To write a C++ program to implement Activity Selection and Huffman Coding
ALGORITHM:
/* 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";
RESULT:
Thus the C++ program Activity Selection & Huffman Coding was written, executed and verified
successfully.