0% found this document useful (0 votes)
2 views99 pages

Advanced Datastructures Lab Manual

The document is a laboratory record notebook for the Advanced Data Structures and Algorithms course at Lord Jegannath College of Engineering and Technology for the academic year 2023-2024. It includes practical exercises on implementing recursive and iterative functions for tree traversal and Fibonacci sequences using C++. The procedures, code examples, and expected outputs for each exercise are detailed throughout the document.

Uploaded by

dhanika
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)
2 views99 pages

Advanced Datastructures Lab Manual

The document is a laboratory record notebook for the Advanced Data Structures and Algorithms course at Lord Jegannath College of Engineering and Technology for the academic year 2023-2024. It includes practical exercises on implementing recursive and iterative functions for tree traversal and Fibonacci sequences using C++. The procedures, code examples, and expected outputs for each exercise are detailed throughout the document.

Uploaded by

dhanika
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/ 99

LORD JEGANNATH COLLEGE OF ENGINEERING AND TECHNOLOGY

PSN Nagar, Ramanathichanputhur, Kumarapuram Thoppur Post-629 402


Kanyakumari District, Tamil Nadu
(Approved by AICTE and Affiliated to Anna University, Chennai)
(Accredited with ‘A’ Grade by NAAC)

RECORD NOTEBOOK

MC4111 – ADVANCED DATA STRUCTURES


AND ALGORITHMS LABORATORY

SEMESTER II

2024-2025
ACADEMIC YEAR : 2023-2024

NAME : ……………………………………

REG.NO : ……………………………….……
LORD JEGANNATH COLLEGE OF ENGINEERING AND TECHNOLOGY
PSN Nagar, Ramanathichanputhur, Kumarapuram Thoppur Post-629 402
Kanyakumari District, Tamil Nadu
(Approved by AICTE and Affiliated to Anna University, Chennai)
(Accredited with ‘A’ Grade by NAAC)

MASTER OF COMPUTER APPLICATIONS


LABORATORY RECORD NOTEBOOK

2024 – 2025

This is to certify that this is a bonafide record of the Practical work done by

Mr./Ms.: _______________________________ Register Number: ___________________________

studying ______ Semester ________ Degree programme in the Department of COMPUTER

APPLICATIONS for the Course _____________________________________________.

Course-in-Charge Head of the Department

Submitted for the University Examination held on ………………………..

Internal Examiner External Examiner


CONTENTS
Ex. Date of Course
Name of the Experiment Page No.
No.: Experiment In-charge Sign.
Program No:
Date:

IMPLEMENTATION OF RECURSIVE FUNCTION FOR TREE


TRAVERSAL AND FIBONACCI

AIM

To implement recursive function for tree traversal and Fibonacci


using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

1
PROGRAM

//IMPLEMENTATION OF RECURSIVE FUNCTION FOR TREE TRAVERSAL


//Pre-Order Tree Traversal Using Recursion

#include <bits/stdc++.h>
using namespace std;

class TreeNode { // tree node is defined


public:
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int data)
{
val = data;
left = NULL;
right = NULL;
}
};

void preorder(TreeNode* root)


{
//base case
if (root == NULL)
return;

//traverse current node firstly


printf("%d ", root->val);

//traverse left sub tree then


preorder(root->left);

//traverse right sub tree lastly


preorder(root->right);
}

2
int main()
{
//building the tree
TreeNode* t = new TreeNode(7);
t->left = new TreeNode(1);
t->left->left = new TreeNode(0);
t->left->right = new TreeNode(3);
t->left->right->left = new TreeNode(2);
t->left->right->right = new TreeNode(5); t-
>left->right->right->left = new TreeNode(4); t-
>left->right->right->right = new TreeNode(6);
t->right = new TreeNode(9); t->right->left =
new TreeNode(8);
t->right->right = new TreeNode(10);

printf("Preorder traversal of the above tree is:\n");


preorder(t);

return 0;
}

OUTPUT

3
//In-Order Tree Traversal Using Recursion

#include<iostream>
using namespace std;
struct node {
int data;
struct node *left;
struct node *right;
};
struct node *createNode(int val) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->data = val;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
}
struct node* insertNode(struct node* node, int val)
{ if (node == NULL) return createNode(val);
if (val < node->data)
node->left = insertNode(node->left, val);
else if (val > node->data)
node->right = insertNode(node->right, val);
return node;
}
int main() {
struct node *root = NULL;
root = insertNode(root, 4);
insertNode(root, 5);
insertNode(root, 2);
insertNode(root, 9);
insertNode(root, 1);

4
insertNode(root, 3);
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root);
return 0;
}

OUTPUT

//Post-Order Tree Traversal Using Recursion

#include <iostream>
#include <string>

using namespace std;

// Template base structure for value


// initializig it by zero in the constructor
template <typename T>
struct Value
{
T m_Value;
Value()
{
m_Value = (T)0;
}
};

5
// Specializing template of value structure for string
// String initialization is different from interger etc.
template <>

struct Value <string>


{
string m_Value;
Value()
{
m_Value.assign("");
}
};

template <typename T>


struct Node
{
Node();
Value<T> m_Value;
Node<T>* m_Left;
Node<T>* m_Right;
};

template <typename T>


Node<T>::Node()
{
m_Left = nullptr;
m_Right = nullptr;
}

// Function to create binary tree.


template <typename T>
Node<T>* createTree()
{
Node<T>* node1 = new Node<T>; node1->m_Value.m_Value = 11;
Node<T>* node2 = new Node<T>; node2->m_Value.m_Value = 22;
Node<T>* node3 = new Node<T>; node3->m_Value.m_Value = 33;
Node<T>* node4 = new Node<T>; node4->m_Value.m_Value = 44;

6
Node<T>* node5 = new Node<T>; node5->m_Value.m_Value = 55;
Node<T>* node6 = new Node<T>; node6->m_Value.m_Value = 66;
Node<T>* node7 = new Node<T>; node7->m_Value.m_Value = 77;
Node<T>* node8 = new Node<T>; node8->m_Value.m_Value = 88;
Node<T>* node9 = new Node<T>; node9->m_Value.m_Value = 99;

node1->m_Left = node2;
node1->m_Right = node3;

node2->m_Left = node4;
node2->m_Right = node5;

node3->m_Left = node6;
node3->m_Right = node7;

node4->m_Left = node8;
node8->m_Left = node9;

return node1;
}

// Postorder traversing using


recursion template <typename T>
void postorder(Node<T>* root)
{
if(nullptr ==
root) return;

postorder<T>(root->m_Left);
postorder<T>(root->m_Right);
cout << root->m_Value.m_Value << " ";
}

int main()
{
Node<int>* root = createTree<int>();
cout << "postorder: ";

7
postorder<int>(root);
cout << endl << endl;
return 0;
}

OUTPUT

//IMPLEMENTATION OF RECURSIVE FUNCTION FOR FIBONACCI

#include <iostream>
using namespace std;
int main() {
int n1=0,n2=1,n3,i,number;
cout<<"Enter the number of elements: ";
cin>>number;
cout<<n1<<" "<<n2<<" "; //printing 0 and 1
for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
cout<<n3<<" ";
n1=n2;

8
n2=n3;
}
return 0;
}

OUTPUT

RESULT

Thus the C++ program was implemented done successfully using


Linux Platform

9
Program No:
Date:

IMPLEMENTATION OF ITERATIVE FUNCTION FOR


TREE TRAVERSAL AND FIBONACCI

AIM

To implement iterative function for tree traversal and Fibonacci


using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

10
//IMPLEMENTATION OF ITERATIVE FUNCTION FOR TREE TRAVERSAL
//In-Order Tree traversal using iterative functions

#include<bits/stdc++.h>
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;
struct Node* right;
Node (int data)
{
this->data = data;
left = right = NULL;
}
};

/* Iterative function for inorder tree traversal */

void inOrder(struct Node *root) {

stack<Node *> s;
Node *curr = root;

while (curr != NULL || s.empty() == false)


{
/* Reach the left most Node of the curr Node */

11
while (curr != NULL)
{

/* place pointer to a tree node on the stack before traversingthe node's left
subtree */
s.push(curr);
curr = curr->left;
}

/* Current must be NULL at this point */


curr = s.top();
s.pop();
cout << curr->data << " ";

/* we have visited the node and itsleft subtree. Now, it's right subtree's turn */
curr = curr->right;

} /* end of while */
}
/* 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);

12
cout<< "The inoder tree Traversal is:";
inOrder(root);
return 0;
}
OUTPUT

//Pre-Order Tree traversal using iterative functions

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

13
}
};

// Iterative function to perform preorder traversal on the tree


void preorderIterative(Node* root)
{
// return if the tree is empty
if (root == nullptr)
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);
}

14
// 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);
cout<<"The pre-order tree traversal is:\n";
preorderIterative(root);
return 0;
}

15
OUTPUT

//Post-Order Tree traversal using iterative functions

#include <bits/stdc++.h>
using namespace std;

// A tree node
struct Node {
int data;
struct Node *left, *right;
};

// A utility function to create a new tree node


struct Node* newNode(int data)
{

struct Node* node = new Node;


node->data = data; node->left =
node->right = NULL; return
node;
}

16
// An iterative function to do postorder traversal of a given binary tree
vector<int> postOrderIterative(struct Node* root)
{
vector<int> postOrderList;

// Check for empty


tree if (root == NULL)

return postOrderList;
stack<Node*> S;
S.push(root);

Node* prev = NULL;


while (!S.empty()) {

auto current = S.top();

/* go down the tree in search of a leaf an if so


process it and pop stack otherwise move down */
if (prev == NULL || prev->left == current

|| prev->right == current) {
if (current->left)

S.push(current->left);
else if (current->right)

S.push(current->right);
else {
S.pop();
postOrderList.push_back(current->data);
}

17
/* go up the tree from left node, if the child is right push it onto stack
otherwise process parent and pop stack */
}
else if (current->left == prev) {
if (current->right)
S.push(current->right);
else {
S.pop();
postOrderList.push_back(current->data);
}

/* go up the tree from right node and after coming back from right node process
parent and pop stack */
}
else if (current->right == prev) {
S.pop();
postOrderList.push_back(current->data);
}
prev = current;
}
return postOrderList;
}

// Driver program to test above


functions int main()
{

struct Node* root = NULL;


root = newNode(1);

18
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);

printf("Post order traversal of binary tree is :\n");


printf("[");

vector<int> postOrderList =
postOrderIterative(root); for (auto it : postOrderList)
cout << it << " ";
printf("]");
return 0;
}

OUTPUT

19
//IMPLEMENTATION OF ITERATIVE FUNCTION FOR 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;
}

20
OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform

21
Program No:
Date:

IMPLEMENTATION OF MERGE SORT AND QUICK SORT

AIM
To implement merge sort and quick sort using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM
//Merge Sort

#include <bits/stdc++.h>
using namespace std;

/* Link list node */


class Node {

22
public:
int data;
Node* next;
};

/* function prototypes */
Node* SortedMerge(Node* a, Node* b);
void FrontBackSplit(Node* source,
Node** frontRef, Node** backRef);

/* sorts the linked list by changing next pointers (not data)


*/ void MergeSort(Node** headRef) {

Node* head = *headRef;


Node* a;
Node* b;
/* Base case -- length 0 or 1 */

if ((head == NULL) || (head->next == NULL)) {


return;
}
/* Split head into 'a' and 'b' sublists */
FrontBackSplit(head, &a, &b);

/* Recursively sort the sublists */


MergeSort(&a);
MergeSort(&b);

23
/* answer = merge the two sorted lists together
*/ *headRef = SortedMerge(a, b);
}

Node* SortedMerge (Node* a, Node* b)


{
Node* result = NULL;

/* Base cases */
if (a == NULL)
return (b);
else if (b == NULL)
return (a);

/* Pick either a or b, and recur */


if (a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next, b);
}
else {
result = b;
result->next = SortedMerge(a, b->next);
}
return (result);
}

24
void FrontBackSplit(Node* source, Node** frontRef, Node** backRef)
{
Node* fast;
Node* slow;
slow = source;
fast = source->next;

while (fast != NULL) {


fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

25
/* Function to insert a node at the beginning of the linked list
*/ void push(Node** head_ref, int new_data) {

/* allocate node */
Node* new_node = new Node();

/* put in the data */


new_node->data = new_data;

/* link the old list off the new node */


new_node->next = (*head_ref);

/* move the head to point to the new node


*/ (*head_ref) = new_node;
}
/* Driver program to test above functions*/
int main()
{
Node* res = NULL;
Node* a = NULL;

/* Let us create a unsorted linked lists to test the


functions Created lists shall be a: 2->3->20->5->10->15 */
push(&a, 15);
push(&a, 10);
push(&a, 5);
push(&a, 20);

26
push(&a, 3);
push(&a, 2);

/* Sort the above created Linked List */


MergeSort(&a);

cout << "Sorted Linked List is: \n";


printList(a);

return 0;
}
OUTPUT

27
//Quick Sort

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

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

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

29
quickSort(arr, 0, n - 1);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}

OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

30
Program No:
Date:

IMPLEMENTATION OF BINARY SEARCH TREE

AIM
To implement Binary Search Tree using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

//IMPLEMENTATION OF BINARY SEARCH TREE


#include <algorithm>
#include <iostream>
using namespace std;
void show(int a[], int arraysize)
{

31
for (int i = 0; i < arraysize; ++i)
cout << a[i] << ",";
}

int main()
{
int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 };
int asize = sizeof(a) / sizeof(a[0]);
cout << "\nThe array is : \n";
show(a, asize);

cout << "\n\nLet's say we want to search for "; cout


<< "\n2 in the array So, we first sort the array";
sort(a, a + asize);

cout << "\n\nThe array after sorting is : \n";


show(a, asize);

cout << "\n\nNow, we do the binary search";


if (binary_search(a, a + 10, 2))
cout << "\nElement found in the array";
else
cout << "\nElement not found in the array";

cout << "\n\nNow, say we want to search for 10";


if (binary_search(a, a + 10, 10))
cout << "\nElement found in the array";
else
cout << "\nElement not found in the array";

32
return 0;
}

OUTPUT

RESULT

Thus the C++ program was implemented done successfully using


Linux Platform.

33
Program No:
Date:

IMPLEMENTATION OF RED-BLACK TREE

AIM
To implement Red-Black Tree using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

//IMPLEMENTATION OF RED-BLACK TREE

PROGRAM
#include<iostream>

using namespace std;

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

35
t->left=NULL;
t->right=NULL;
t->color='r';
p=root;
q=NULL;
if(root==NULL)
{
root=t;
t->parent=NULL;
}
else
{
while(p!=NULL)
{
q=p;
if(p->key<t->key)
p=p->right;
else
p=p->left;
}
t->parent=q;
if(q->key<t->key)
q->right=t;
else
q->left=t;
}
insertfix(t);
}
void RBtree::insertfix(node *t)
{
node *u;
if(root==t)
{
t->color='b';
return;
}
while(t->parent!=NULL&&t->parent->color=='r')

36
{
node *g=t->parent->parent;
if(g->left==t->parent)
{
if(g->right!=NULL)
{
u=g->right;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';
t=g;
}
}
else
{
if(t->parent->right==t)
{
t=t->parent;
leftrotate(t);
}
t->parent->color='b';
g->color='r';
rightrotate(g);
}
}
else
{
if(g->left!=NULL)
{
u=g->left;
if(u->color=='r')
{
t->parent->color='b';
u->color='b';
g->color='r';

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

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

39
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')

40
{
if(p->parent->left==p)
{
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')
{

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

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

43
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;
}
return y;
}

void RBtree::disp()
{
display(root);

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

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

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

47
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

48
49
RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

50
Program No:
Date:

HEAP IMPLEMENTATION

AIM
To implement Heap implementation using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

//IMPLEMENTATION OF HEAP IMPLEMENTATION


#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class DaryHeap
51
{
private:
int d;
int currentSize;
int size;
int *array;
public:
DaryHeap(int capacity, int numKids)
{
currentSize = 0;
d = numKids;
size = capacity + 1;
array = new int[capacity + 1];
for (int i = 0 ; i < capacity + 1; i++)
array[i] = -1;
}

DaryHeap(int* array, int numKids)


{
int i = 0;
while (array[i] != -1)
i++;
currentSize = i;
this->array = array;
this->d = numKids;
buildHeap();

52
}
bool isEmpty()
{
return currentSize == 0;
}
bool isFull()
{
return currentSize == size;
}
void makeEmpty( )
{
currentSize = 0;
}
int parent(int i)
{
return (i - 1) / d;
}
int kthChild(int i, int k)
{
return d * i + k;
}
void insert(int x)
{
if (isFull())
{
cout<<"Array Out of Bounds"<<endl;

53
return;
}
int hole = currentSize;
currentSize++;
array[hole] = x;
percolateUp(hole);
}
int findMin()
{
if (isEmpty())
{
cout<<"Array Underflow"<<endl;
return 0;
}
return array[0];
}
int Delete(int hole)
{
if (isEmpty())
{
cout<<"Array Underflow"<<endl;
return 0;
}
int keyItem = array[hole];
array[hole] = array[currentSize - 1];
currentSize--;

54
percolateDown( hole );
return keyItem;
}
void buildHeap()
{
for (int i = currentSize - 1 ; i >= 0; i--)
percolateDown(i);
}

void percolateDown(int hole)


{
int child;
int tmp = array[hole];
for ( ; kthChild(hole, 1) < currentSize; hole = child)
{
child = smallestChild( hole );
if (array[child] < tmp)
array[hole] = array[child];
else
break;
}
array[hole] = tmp;
}
int smallestChild(int hole)
{
int bestChildYet = kthChild(hole, 1);

55
int k = 2;
int candidateChild = kthChild(hole, k);
while ((k <= d) && (candidateChild < currentSize))
{
if (array[candidateChild] < array[bestChildYet])
bestChildYet = candidateChild;
k++;
candidateChild = kthChild(hole, k);
}
return bestChildYet;
}
void percolateUp(int hole)
{
int tmp = array[hole];
for (; hole > 0 && tmp < array[parent(hole)]; hole = parent(hole))
array[hole] = array[ parent(hole) ];
array[hole] = tmp;
}
void printHeap()
{
cout<<"\nHeap = ";
for (int i = 0; i < currentSize; i++)
cout<<array[i]<<" ";
cout<<endl;
}
};

56
/*

* Main
*/
int main()
{

cout<<"Dary Heap Test\n\n";


cout<<"Enter size and D of Dary Heap:
"; int size, num, choice, val;
cin>>size>>num;

DaryHeap th(size,
num); char ch;
do
{

cout<<"\nDary Heap Operations\n";


cout<<"1. Insert "<<endl; cout<<"2.
Delete"<<endl; cout<<"3. Check
full"<<endl; cout<<"4. Check
empty"<<endl; cout<<"5.
Clear"<<endl;
bool chk;

cout<<"Enter your Choice: ";


cin>>choice;
switch (choice)
{
case 1:
cout<<"Enter integer element to insert: ";

57
cin>>val;
th.insert(val);
break;
case 2:
cout<<"Enter delete position: ";
cin>>val;
th.Delete(val - 1);
break;
case 3:
if (th.isFull())
cout<<"The Heap is Full"<<endl;
else
cout<<"The Heap is not Full"<<endl;
break;
case 4 :
if (th.isEmpty())
cout<<"The Heap is Empty"<<endl;
else
cout<<"The Heap is not Empty"<<endl;
break;
case 5 :
th.makeEmpty();
cout<<"Heap Cleared\n";
break;
default :
cout<<"Wrong Entry \n ";

58
break;
}
th.printHeap();

cout<<"\nDo you want to continue (Type y or n) \n";


cin>>ch;
}
while (ch == 'Y'|| ch == 'y');
return 0;
OUTPUT

59
60
RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

61
Program No:
Date:

FIBONACCI HEAP IMPLEMENTATION

AIM
To implement Fibonacci Heap implementation using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM
// FIBONACCI HEAP IMPLEMENTATION

// C++ program to demonstrate building and inserting in a Fibonacci heap


#include <cstdlib>

#include <iostream>
#include <malloc.h>
using namespace std;

62
struct node {
node* parent;
node* child;
node* left;
node* right;
int key;
};

// Creating min pointer as "mini"


struct node* mini = NULL;

// Declare an integer for number of nodes in the


heap int no_of_nodes = 0;

// Function to insert a node in heap


void insertion(int val)
{

struct node* new_node = (struct node*)malloc(sizeof(struct


node)); new_node->key = val;
new_node->parent = NULL;
new_node->child = NULL;
new_node->left = new_node;
new_node->right = new_node;
if (mini != NULL) {
(mini->left)->right = new_node;
new_node->right = mini;
new_node->left = mini->left;

63
mini->left = new_node;
if (new_node->key < mini->key)
mini = new_node;
}
else {
mini = new_node;
}
}

// Function to display the heap


void display(struct node* mini)
{
node* ptr = mini;
if (ptr == NULL)
cout << "The Heap is Empty" << endl;

else {

cout << "The root nodes of Heap are: " << endl;
do {
cout << ptr->key;
ptr = ptr->right;
if (ptr != mini) {
cout << "-->";
}

} while (ptr != mini && ptr->right != NULL);


cout << endl
<< "The heap has " << no_of_nodes << " nodes" << endl;

64
}
}

// Function to find min node in the heap


void find_min(struct node* mini)
{
cout << "min of heap is: " << mini->key << endl;
}

// Driver code
int main()
{

no_of_nodes = 7;
insertion(4);
insertion(3);
insertion(7);
insertion(5);
insertion(2);
insertion(1);
insertion(10);
display(mini);
find_min(mini);
return 0;
}

65
OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

66
Program No:
Date:

GRAPH TRAVERSAL

AIM
To implement Graph Traversal implemantation using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

// GRAPH TRAVERSAL
// Breadth first Traversal
#include <bits/stdc++.h>
using namespace std;

// This class represents a directed graph using

67
// adjacency list representation
class Graph {
int V; // No. of vertices

// Pointer to an array containing adjacency


// lists
vector<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.resize(V);
}

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


{

68
adj[v].push_back(w); // Add w to v’s list.
}

void Graph::BFS(int s)
{

// Mark all the vertices as not visited


vector<bool> visited;
visited.resize(V, 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);

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 (auto adjecent : adj[s]) {

69
if (!visited[adjecent]) {
visited[adjecent] = true;
queue.push_back(adjecent);
}
}
}
}

// 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(0, 2);
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;
}

70
OUTPUT

//Depth First Traversal

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

class DFSGraph
{
int V; // No. of vertices
list<int> *adjList; // adjacency list

void DFS_util(int v, bool visited[]); // A function used by DFS


public:

// class Constructor
DFSGraph(int V)
{
this->V = V;
adjList = new list<int>[V];
}

// function to add an edge to graph


void addEdge(int v, int w){

71
adjList[v].push_back(w); // Add w to v’s list.
}

void DFS(); // DFS traversal function


};
void DFSGraph::DFS_util(int v, bool visited[])
{

// current node v is visited


visited[v] = true;
cout << v << " ";

// recursively process all the adjacent vertices of the


node list<int>::iterator i;

for(i = adjList[v].begin(); i != adjList[v].end(); ++i)


if(!visited[*i])
DFS_util(*i, visited);
}

// DFS traversal
void DFSGraph::DFS()
{

// initially none of the vertices are visited


bool *visited = new bool[V];

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


visited[i] = false;

72
// explore the vertices one by one by recursively calling DFS_util
for (int i = 0; i < V; i++)

if (visited[i] == false)
DFS_util(i, visited);

int main()
{

// Create a graph

DFSGraph gdfs(5);

gdfs.addEdge(0, 1);

gdfs.addEdge(0, 2);

gdfs.addEdge(0, 3);

gdfs.addEdge(1, 2);

gdfs.addEdge(2, 4);

gdfs.addEdge(3, 3);

gdfs.addEdge(4, 4);

cout << "Depth-first traversal for the given


graph:"<<endl; gdfs.DFS();

return 0;
}

73
OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

74
Program No:
Date:

SPANNING TREE IMPLEMENTATION

AIM
To implement Spanning tree using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

// SPANNING TREE IMPLEMENTATION


#include <iostream>
#include<bits/stdc++.h>
#include <cstring>
using namespace std;

75
#define V 7
int main () {
int G[V][V] = {
{0,28,0,0,0,10,0},
{28,0,16,0,0,0,14},
{0,16,0,12,0,0,0},
{0,0,12,22,0,18},
{0,0,0,22,0,25,24},
{10,0,0,0,25,0,0},
{0,14,0,18,24,0,0}
};

int edge;
int visit[V];
for(int i=0;i<V;i++){
visit[i]=false;
}
edge = 0;
visit[0] = true;
int x;
int y;
cout << "Edge" << " : " << "Weight";
cout << endl;
while (edge < V - 1) {
int min = INT_MAX;
x = 0;

76
y = 0;
for (int i = 0; i < V; i++) {
if (visit[i]) {
for (int j = 0; j < V; j++) {
if (!visit[j] && G[i][j]) {
if (min > G[i][j]) {
min = G[i][j];
x = i;
y = j;
}

}
}
}
}
cout << x << " ---> " << y << " : " << G[x][y];
cout << endl;
visit[y] = true;
edge++;
}
return 0;
}

77
OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

78
Program No:
Date:

SHORTEST PATH ALGORITHM

AIM
To implement Shortest Path Algorithm using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

// SHORTEST PATH ALGORITHM


// Dijkstra's algorithm
#include<iostream>
#include<climits>
using namespace std;
#define vertex 7
79
int minimumDist(int dist[], bool Dset[])
{
int min=INT_MAX,index;
for(int v=0;v<vertex;v++)
{
if(Dset[v]==false && dist[v]<=min)
{
min=dist[v];
index=v;
}
}
return index;
}
void dijkstra(int graph[vertex][vertex],int src)
{
int dist[vertex];
bool Dset[vertex];
for(int i=0;i<vertex;i++)
{
dist[i]=INT_MAX;
Dset[i]=false;
}
dist[src]=0;
for(int c=0;c<vertex;c++)
{
int u=minimumDist(dist,Dset);

80
Dset[u]=true;
for(int v=0;v<vertex;v++)

if(!Dset[v] && graph[u][v] && dist[u]!=INT_MAX &&


dist[u]+graph[u][v]<dist[v])
dist[v]=dist[u]+graph[u][v];
}
}
cout<<"Vertex\t\tDistance from source"<<endl;
for(int i=0;i<vertex;i++)
{
char c=65+i;
cout<<c<<"\t\t"<<dist[i]<<endl;
}
}
int main()
{
int
graph[vertex][vertex]={{0,5,3,0,0,0,0},{0,0,2,0,3,0,1},{0,0,0,7,7,0,0},{2,0,0,0,0,6,0},{
0,0,0,2,0,1,0},{0,0,0,0,0,0,0}, {0,0,0,0,1,0,0}};
dijkstra(graph,0);
return 0;
}

81
OUTPUT

// Bellman Ford Algorithm


#include <bits/stdc++.h>
using namespace std;

struct Edge {
int src, dest, weight;
};
struct Graph {
int V, E;
struct Edge* edge;
};

struct Graph* createGraph(int V, int E)

82
{
struct Graph* graph = new Graph;
graph->V = V;
graph->E = E;
graph->edge = new Edge[E];
return graph;
}
void printArr(int dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %d\n", i, dist[i]);
}
void BellmanFord(struct Graph* graph, int src)
{
int V = graph->V;
int E = graph->E;
int dist[V];

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


dist[i] = INT_MAX;
dist[src] = 0;

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


for (int j = 0; j < E; j++) {
int u = graph->edge[j].src;

83
int v = graph->edge[j].dest;
int weight = graph->edge[j].weight;
if (dist[u] != INT_MAX

&& dist[u] + weight < dist[v])


dist[v] = dist[u] + weight;
}
}
for (int i = 0; i < E; i++) {
int u = graph->edge[i].src;
int v = graph->edge[i].dest;
int weight = graph->edge[i].weight;
if (dist[u] != INT_MAX
&& dist[u] + weight < dist[v]) {

printf("Graph contains negative weight


cycle"); return;
}
}
printArr(dist, V);
return;
}
int main()
{
int V = 5;
int E = 8;
struct Graph* graph = createGraph(V, E);
graph->edge[0].src = 0;

84
graph->edge[0].dest = 1;
graph->edge[0].weight = -1;
graph->edge[1].src = 0;
graph->edge[1].dest = 2;
graph->edge[1].weight = 4;
graph->edge[2].src = 1;
graph->edge[2].dest = 2;
graph->edge[2].weight = 3;
graph->edge[3].src = 1;
graph->edge[3].dest = 3;
graph->edge[3].weight = 2;
graph->edge[4].src = 1;
graph->edge[4].dest = 4;
graph->edge[4].weight = 2;
graph->edge[5].src = 3;
graph->edge[5].dest = 2;
graph->edge[5].weight = 5;
graph->edge[6].src = 3;
graph->edge[6].dest = 1;
graph->edge[6].weight = 1;
graph->edge[7].src = 4;
graph->edge[7].dest = 3;
graph->edge[7].weight = -3;
BellmanFord(graph, 0);
return 0;
}

85
OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

86
Program No:
Date:

IMPLEMENTATION OF MATRIX CHAIN MULTIPLICATION

AIM
To implement Matrix Chain Multiplication using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

// Matrix Chain Multiplication


#include &lt;limits.h&gt;
#include &lt;stdio.h&gt;

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


int MatrixChainOrder(int p[], int i, int j)
87
{
if (i == j)
return 0;
int k;
int min = INT_MAX;
int count;

// place parenthesis at different places between first


// and last matrix, recursively calculate count of
// multiplications for each parenthesis placement and
// return the minimum count
for (k = i; k &lt; j; k++) {
count = MatrixChainOrder(p, i, k) +
MatrixChainOrder(p, k + 1, j) +
p[i - 1] * p[k] * p[j];

if (count &lt; min)


min = count;

// Return minimum count


return min;
}

// Driver program to test above function

88
int main()
{
int arr[] = { 1, 2, 3, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);

printf(&quot;Minimum number of multiplications is %d


&quot;, MatrixChainOrder(arr, 1, n - 1));

getchar();
return 0;
}

OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

89
Program No:
Date:

IMPLEMENTATION OF ACTIVITY SELECTION AND


HUFFMAN CODING

AIM
To implement Activity Selection and Huffman Code using C++ Program

PROCEDURE
Step 1: Open Ubuntu OS.
Step 2: Open terminal
Step 3: Check gcc version using the command gcc - -version
Step 4: Install/Update gcc use the command sudo apt install build-essential

Step 5: Use the Command for writing the Program touch filename.cpp
(Open the file using notepad & Save the Program (File Name can be
anything but it should end with .cpp extension)
Step 6: To Compile the Program use the command g++ filename.cpp
Step 7: To Run the Program ./a.out
Step 8: Output will be displayed in the Terminal.

PROGRAM

// Activity Selection
include <bits/stdc++.h>
using namespace std;

// Prints a maximum set of activities that can be done by a


// single person, one at a time.
90
void printMaxActivities(int s[], int f[], int n)
{
int i, j;

cout << "Following activities are selected" << endl;

// The first activity always gets


selected i = 0;
cout << i << " ";

// Consider rest of the activities


for (j = 1; j < n; j++) {
// If this activity has start time greater than or
// equal to the finish time of previously selected
// activity, then select it
if (s[j] >= f[i]) {
cout << j << " ";
i = j;
}
}
}

// Driver code
int main()
{
int s[] = { 1, 3, 0, 5, 8, 5 };

91
int f[] = { 2, 4, 6, 7, 9, 9 };
int n = sizeof(s) / sizeof(s[0]);

// Function call
printMaxActivities(s, f,
n); return 0;
}

OUTPUT

//Huffman Coding
#include <bits/stdc++.h>
using namespace std;

struct MinHeapNode
{
92
char d;
unsigned frequency;
MinHeapNode *lChild, *rChild;

MinHeapNode(char d, unsigned frequency)

{
lChild = rChild = NULL;
this->d = d;
this->frequency = frequency;
}
};
//function to compare
struct compare
{
bool operator()(MinHeapNode *l, MinHeapNode *r)
{
return (l->frequency > r->frequency);
}
};

void printCodes(struct MinHeapNode *root, string str)


{
if (!root)
return;

93
if (root->d != '$')
cout << root->d << ": " << str << "\n";

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


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

void HuffmanCodes(char d[], int frequency[], int size)


{
struct MinHeapNode *lChild, *rChild, *top;

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

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


minHeap.push(new MinHeapNode(d[i], frequency[i]));

while (minHeap.size() != 1)
{
lChild = minHeap.top();
minHeap.pop();

rChild = minHeap.top();
minHeap.pop();

top = new MinHeapNode('$', lChild->frequency + rChild->frequency);

94
top->lChild = lChild;
top->rChild = rChild;

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

int main()
{

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


int frequency[] = {5, 9, 12, 13, 16, 45};

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

HuffmanCodes(arr, frequency, size);

return 0;
}

95
OUTPUT

RESULT

Thus the C++ program was implemented done successfully using Linux
Platform.

96

You might also like