0% found this document useful (0 votes)
2 views

DSA LAB PRINT

The document provides implementations of various algorithms including recursive and iterative tree traversals, Fibonacci series, merge sort, quick sort, a binary search tree, and a red-black tree. Each section contains code snippets in C++ demonstrating the respective algorithms and data structures. The examples illustrate how to create, traverse, and manipulate these data structures effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

DSA LAB PRINT

The document provides implementations of various algorithms including recursive and iterative tree traversals, Fibonacci series, merge sort, quick sort, a binary search tree, and a red-black tree. Each section contains code snippets in C++ demonstrating the respective algorithms and data structures. The examples illustrate how to create, traverse, and manipulate these data structures effectively.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

Implementation of recursive function for tree traversal and Fibonacci.

Tree Traversal:
#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);
insertNode(root, 3);
cout<<"In-Order traversal of the Binary Search Tree is: ";
inorder(root);
return 0;
}
Fibanocci Series:
#include<iostream>
using namespace std;
int fib(int n) {
if (n <= 1)
return n;
return fib(n-1) + fib(n-2);
}
int main () {
int n = 10, i;
for(i=0;i<n;i++)
cout<<fib(i)<<" ";
return 0;
}
Implementation of iteration function for tree traversal and Fibonacci.

Tree Traversal:
#include <iostream>
#include <stack>
using namespace std;

// Data structure to store a binary tree node


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

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

// Iterative function to perform postorder traversal on the tree


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

// create an empty stack and push the root node


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

// create another stack to store postorder traversal


stack<int> out;

// loop till stack is empty


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

out.push(curr->data);

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

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

// print postorder traversal


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

int main()
{
/* Construct the following tree
1
/ \
/ \
2 3
/ / \
/ / \
4 5 6
/\
/ \
7 8
*/

Node* root = new Node(1);


root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->left = new Node(7);
root->right->left->right = new Node(8);

postorderIterative(root);

return 0;
}

Fibanocci Series:
#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;
}

Implementation of Merge Sort and Quick Sort.


Merge Sort:
#include <iostream>
using namespace std;

// Merges two subarrays of array[].


// First subarray is arr[begin..mid]
// Second subarray is arr[mid+1..end]
void merge(int array[], int const left, int const mid, int const right)
{
auto const subArrayOne = mid - left + 1;
auto const subArrayTwo = right - mid;

// Create temp arrays


auto *leftArray = new int[subArrayOne],
*rightArray = new int[subArrayTwo];

// Copy data to temp arrays leftArray[] and rightArray[]


for (auto i = 0; i < subArrayOne; i++)
leftArray[i] = array[left + i];
for (auto j = 0; j < subArrayTwo; j++)
rightArray[j] = array[mid + 1 + j];

auto indexOfSubArrayOne = 0, // Initial index of first sub-array


indexOfSubArrayTwo = 0; // Initial index of second sub-array
int indexOfMergedArray = left; // Initial index of merged array

// Merge the temp arrays back into array[left..right]


while (indexOfSubArrayOne < subArrayOne && indexOfSubArrayTwo <
subArrayTwo) {
if (leftArray[indexOfSubArrayOne] <= rightArray[indexOfSubArrayTwo]) {
array[indexOfMergedArray] = leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
}
else {
array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
}
indexOfMergedArray++;
}
// Copy the remaining elements of
// left[], if there are any
while (indexOfSubArrayOne < subArrayOne) {
array[indexOfMergedArray] = leftArray[indexOfSubArrayOne];
indexOfSubArrayOne++;
indexOfMergedArray++;
}
// Copy the remaining elements of
// right[], if there are any
while (indexOfSubArrayTwo < subArrayTwo) {
array[indexOfMergedArray] = rightArray[indexOfSubArrayTwo];
indexOfSubArrayTwo++;
indexOfMergedArray++;
}
}

// begin is for left index and end is


// right index of the sub-array
// of arr to be sorted */
void mergeSort(int array[], int const begin, int const end)
{
if (begin >= end)
return; // Returns recursively
auto mid = begin + (end - begin) / 2;
mergeSort(array, begin, mid);
mergeSort(array, mid + 1, end);
merge(array, begin, mid, end);
}
// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
for (auto i = 0; i < size; i++)
cout << A[i] << " ";
}

// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
auto arr_size = sizeof(arr) / sizeof(arr[0]);
cout << "Given array is \n";
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);

cout << "\nSorted array is \n";


printArray(arr, arr_size);
return 0;
}

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

// A utility function to swap two elements


void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}

/* This function takes last element as pivot, places


the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element and indicates the right position of pivot
found so far

for (int j = low; j <= high - 1; j++)


{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

/* The main function that implements QuickSort


arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}

// Driver Code
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}

Implementation of a Binary Search Tree.


#include <iostream>
using namespace std;

class BST {
int data;
BST *left, *right;

public:
// Default constructor.
BST();

// Parameterized constructor.
BST(int);

// Insert function.
BST* Insert(BST*, int);

// Inorder traversal.
void Inorder(BST*);
};

// Default Constructor definition.


BST ::BST()
: data(0)
, left(NULL)
, right(NULL)
{
}

// Parameterized Constructor definition.


BST ::BST(int value)
{
data = value;
left = right = NULL;
}
// Insert function definition.
BST* BST ::Insert(BST* root, int value)
{
if (!root) {
// Insert the first node, if root is NULL.
return new BST(value);
}
// Insert data.
if (value > root->data) {
// Insert right node data, if the 'value'
// to be inserted is greater than 'root' node data.

// Process right nodes.


root->right = Insert(root->right, value);
}
else {
// Insert left node data, if the 'value'
// to be inserted is greater than 'root' node data.

// Process left nodes.


root->left = Insert(root->left, value);
}
// Return 'root' node, after insertion.
return root;
}
// Inorder traversal function.
// This gives data in sorted order.
void BST ::Inorder(BST* root)
{
if (!root) {
return;
}
Inorder(root->left);
cout << root->data << endl;
Inorder(root->right);
}

// Driver code
int main()
{
BST b, *root = NULL;
root = b.Insert(root, 50);
b.Insert(root, 30);
b.Insert(root, 20);
b.Insert(root, 40);
b.Insert(root, 70);
b.Insert(root, 60);
b.Insert(root, 80);

b.Inorder(root);
return 0;
}

Red-Black Tree Implementation.


#include <iostream>
using namespace std;

struct Node {
int data;
Node *parent;
Node *left;
Node *right;
int color;
};

typedef Node *NodePtr;

class RedBlackTree {
private:
NodePtr root;
NodePtr TNULL;

void initializeNULLNode(NodePtr
node, NodePtr parent) {
node->data = 0;
node->parent = parent;
node->left = nullptr;
node->right = nullptr;
node->color = 0;
}

// Preorder
void preOrderHelper(NodePtr node) {
if (node != TNULL) {
cout << node->data << " ";
preOrderHelper(node->left);
preOrderHelper(node->right);
}
}

// Inorder
void inOrderHelper(NodePtr node) {
if (node != TNULL) {
inOrderHelper(node->left);
cout << node->data << " ";
inOrderHelper(node->right);
}
}
// Post order
void postOrderHelper(NodePtr node) {
if (node != TNULL) {
postOrderHelper(node->left);
postOrderHelper(node->right);
cout << node->data << " ";
}
}

NodePtr searchTreeHelper(NodePtr
node, int key) {
if (node == TNULL || key == node-
>data) {
return node;
}

if (key < node->data) {


return searchTreeHelper(node->left,
key);
}
return searchTreeHelper(node->right,
key);
}

// For balancing the tree after deletion


void deleteFix(NodePtr x) {
NodePtr s;
while (x != root && x->color == 0) {
if (x == x->parent->left) {
s = x->parent->right;
if (s->color == 1) {
s->color = 0;
x->parent->color = 1;
leftRotate(x->parent);
s = x->parent->right;
}

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


>color == 0) {
s->color = 1;
x = x->parent;
} else {
if (s->right->color == 0) {
s->left->color = 0;
s->color = 1;
rightRotate(s);
s = x->parent->right;
}

s->color = x->parent->color;
x->parent->color = 0;
s->right->color = 0;
leftRotate(x->parent);
x = root;
}
} else {
s = x->parent->left;
if (s->color == 1) {
s->color = 0;
x->parent->color = 1;
rightRotate(x->parent);
s = x->parent->left;
}

if (s->right->color == 0 && s-
>right->color == 0) {
s->color = 1;
x = x->parent;
} else {
if (s->left->color == 0) {
s->right->color = 0;
s->color = 1;
leftRotate(s);
s = x->parent->left;
}

s->color = x->parent->color;
x->parent->color = 0;
s->left->color = 0;
rightRotate(x->parent);
x = root;
}
}
}
x->color = 0;
}
void rbTransplant(NodePtr u, NodePtr
v) {
if (u->parent == nullptr) {
root = v;
} else if (u == u->parent->left) {
u->parent->left = v;
} else {
u->parent->right = v;
}
v->parent = u->parent;
}

void deleteNodeHelper(NodePtr node,


int key) {
NodePtr z = TNULL;
NodePtr x, y;
while (node != TNULL) {
if (node->data == key) {
z = node;
}

if (node->data <= key) {


node = node->right;
} else {
node = node->left;
}
}

if (z == TNULL) {
cout << "Key not found in the tree"
<< endl;
return;
}

y = z;
int y_original_color = y->color;
if (z->left == TNULL) {
x = z->right;
rbTransplant(z, z->right);
} else if (z->right == TNULL) {
x = z->left;
rbTransplant(z, z->left);
} else {
y = minimum(z->right);
y_original_color = y->color;
x = y->right;
if (y->parent == z) {
x->parent = y;
} else {
rbTransplant(y, y->right);
y->right = z->right;
y->right->parent = y;
}

rbTransplant(z, y);
y->left = z->left;
y->left->parent = y;
y->color = z->color;
}
delete z;
if (y_original_color == 0) {
deleteFix(x);
}
}

// For balancing the tree after insertion


void insertFix(NodePtr k) {
NodePtr u;
while (k->parent->color == 1) {
if (k->parent == k->parent->parent-
>right) {
u = k->parent->parent->left;
if (u->color == 1) {
u->color = 0;
k->parent->color = 0;
k->parent->parent->color = 1;
k = k->parent->parent;
} else {
if (k == k->parent->left) {
k = k->parent;
rightRotate(k);
}
k->parent->color = 0;
k->parent->parent->color = 1;
leftRotate(k->parent->parent);
}
} else {
u = k->parent->parent->right;
if (u->color == 1) {
u->color = 0;
k->parent->color = 0;
k->parent->parent->color = 1;
k = k->parent->parent;
} else {
if (k == k->parent->right) {
k = k->parent;
leftRotate(k);
}
k->parent->color = 0;
k->parent->parent->color = 1;
rightRotate(k->parent->parent);
}
}
if (k == root) {
break;
}
}
root->color = 0;
}

void printHelper(NodePtr root, string


indent, bool last) {
if (root != TNULL) {
cout << indent;
if (last) {
cout << "R----";
indent += " ";
} else {
cout << "L----";
indent += "| ";
}

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


"BLACK";
cout << root->data << "(" << sColor
<< ")" << endl;
printHelper(root->left, indent, false);
printHelper(root->right, indent, true);
}
}
public:
RedBlackTree() {
TNULL = new Node;
TNULL->color = 0;
TNULL->left = nullptr;
TNULL->right = nullptr;
root = TNULL;
}

void preorder() {
preOrderHelper(this->root);
}

void inorder() {
inOrderHelper(this->root);
}

void postorder() {
postOrderHelper(this->root);
}

NodePtr searchTree(int k) {
return searchTreeHelper(this->root, k);
}

NodePtr minimum(NodePtr node) {


while (node->left != TNULL) {
node = node->left;
}
return node;
}

NodePtr maximum(NodePtr node) {


while (node->right != TNULL) {
node = node->right;
}
return node;
}

NodePtr successor(NodePtr x) {
if (x->right != TNULL) {
return minimum(x->right);
}
NodePtr y = x->parent;
while (y != TNULL && x == y->right)
{
x = y;
y = y->parent;
}
return y;
}

NodePtr predecessor(NodePtr x) {
if (x->left != TNULL) {
return maximum(x->left);
}

NodePtr y = x->parent;
while (y != TNULL && x == y->left)
{
x = y;
y = y->parent;
}

return y;
}

void leftRotate(NodePtr x) {
NodePtr y = x->right;
x->right = y->left;
if (y->left != TNULL) {
y->left->parent = x;
}
y->parent = x->parent;
if (x->parent == nullptr) {
this->root = y;
} else if (x == x->parent->left) {
x->parent->left = y;
} else {
x->parent->right = y;
}
y->left = x;
x->parent = y;
}

void rightRotate(NodePtr x) {
NodePtr y = x->left;
x->left = y->right;
if (y->right != TNULL) {
y->right->parent = x;
}
y->parent = x->parent;
if (x->parent == nullptr) {
this->root = y;
} else if (x == x->parent->right) {
x->parent->right = y;
} else {
x->parent->left = y;
}
y->right = x;
x->parent = y;
}

// Inserting a node
void insert(int key) {
NodePtr node = new Node;
node->parent = nullptr;
node->data = key;
node->left = TNULL;
node->right = TNULL;
node->color = 1;

NodePtr y = nullptr;
NodePtr x = this->root;

while (x != TNULL) {
y = x;
if (node->data < x->data) {
x = x->left;
} else {
x = x->right;
}
}

node->parent = y;
if (y == nullptr) {
root = node;
} else if (node->data < y->data) {
y->left = node;
} else {
y->right = node;
}

if (node->parent == nullptr) {
node->color = 0;
return;
}

if (node->parent->parent == nullptr) {
return;
}

insertFix(node);
}

NodePtr getRoot() {
return this->root;
}

void deleteNode(int data) {


deleteNodeHelper(this->root, data);
}

void printTree() {
if (root) {
printHelper(this->root, "", true);
}
}
};
int main() {
RedBlackTree bst;
bst.insert(55);
bst.insert(40);
bst.insert(65);
bst.insert(60);
bst.insert(75);
bst.insert(57);

bst.printTree();
cout << endl
<< "After deleting" << endl;
bst.deleteNode(40);
bst.printTree();
}
Heap Implementation.
#include <iostream>

using namespace std;

// To heapify a subtree rooted with node i which is


// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger than largest so far


if (r < n && arr[r] > arr[largest])
largest = r;

// If largest is not root


if (largest != i) {
swap(arr[i], arr[largest]);

// Recursively heapify the affected sub-tree


heapify(arr, n, largest);
}
}

// main function to do heap sort


void heapSort(int arr[], int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// One by one extract an element from heap


for (int i = n - 1; i > 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);

// call max heapify on the reduced heap


heapify(arr, i, 0);
}
}

/* A utility function to print array of size n */


void printArray(int arr[], int n)
{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << "\n";
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

cout << "Sorted array is \n";


printArray(arr, n);
}

Fibonacci Heap Implementation.


#include <cmath>
#include <cstdlib>
#include <iostream>

using namespace std;

// Node creation
struct node {
int n;
int degree;
node *parent;
node *child;
node *left;
node *right;
char mark;

char C;
};

// Implementation of Fibonacci heap


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

// Create linking
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 Operation
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 the heap


int FibonacciHeap::Display(node *H) {
node *p = H;
if (p == NULL) {
cout << "Empty Heap" << endl;
return 0;
}
cout << "Root Nodes: " << endl;

do {
cout << p->n;
p = p->right;
if (p != H) {
cout << "-->";
}
} while (p != H && p->right != NULL);
cout << endl;
}

// Extract min
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;
}

// Consolidation Function
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 Operation


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

// Cutting Function
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 cut
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);
}
}
}

// Search function
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;
}

// Deleting key
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;
}

int main() {
int n, m, l;
FibonacciHeap fh;
node *p;
node *H;
H = fh.InitializeHeap();

p = fh.Create_node(7);
H = fh.Insert(H, p);
p = fh.Create_node(3);
H = fh.Insert(H, p);
p = fh.Create_node(17);
H = fh.Insert(H, p);
p = fh.Create_node(24);
H = fh.Insert(H, p);

fh.Display(H);

p = fh.Extract_Min(H);
if (p != NULL)
cout << "The node with minimum key: " << p->n << endl;
else
cout << "Heap is empty" << endl;

m = 26;
l = 16;
fh.Decrease_key(H, m, l);

m = 16;
fh.Delete_key(H, m);
}

Graph Traversals.
Breadth First Search

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

Depth First Search


#include <bits/stdc++.h>
class Graph {
public:
map<int, bool> visited;
map<int, list<int> > adj;

void addEdge(int v, int w);

void DFS(int v);


};

void Graph : addEdge(int v, int


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

void Graph::DFS(int v)
{
// Mark the current node
as visited and
// print it
visited[v] = true;
cout << v << " ";

// Recur for all the


vertices adjacent
// to this vertex
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;
}

Spanning Tree Implementation.


#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


const int MAX = 1e6-1;
int root[MAX];
const int nodes = 4, edges = 5;
pair <long long, pair<int, int> > p[MAX];

int parent(int a) //find the parent of the given node


{
while(root[a] != a)
{
root[a] = root[root[a]];
a = root[a];
}
return a;
}

void union_find(int a, int b) //check if the given two vertices are in


the same “union” or not
{
int d = parent(a);
int e = parent(b);
root[d] = root[e];
}

long long kruskal()


{
int a, b;
long long cost, minCost = 0;
for(int i = 0 ; i < edges ; ++i)
{
a = p[i].second.first;
b = p[i].second.second;
cost = p[i].first;
if(parent(a) != parent(b)) //only select edge if it does not create a
cycle (ie the two nodes forming it have different root nodes)
{
minCost += cost;
union_find(a, b);
}
}
return minCost;
}

int main()
{
int x, y;
long long weight, cost, minCost;
for(int i = 0;i < MAX;++i) //initialize the array groups
{
root[i] = i;
}
p[0] = make_pair(10, make_pair(0, 1));
p[1] = make_pair(18, make_pair(1, 2));
p[2] = make_pair(13, make_pair(2, 3));
p[3] = make_pair(21, make_pair(0, 2));
p[4] = make_pair(22, make_pair(1, 3));
sort(p, p + edges); //sort the array of edges
minCost = kruskal();
cout << "Minimum cost is: "<< minCost << endl;
return 0;
}

Shortest Path Algorithms (Dijkstra's algorithm, Bellman Ford Algorithm).


Dijkstra's algorithm:

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

int miniDist(int distance[], bool Tset[]) // finding minimum distance


{
int minimum=INT_MAX,ind;

for(int k=0;k<6;k++)
{
if(Tset[k]==false && distance[k]<=minimum)
{
minimum=distance[k];
ind=k;
}
}
return ind;
}

void DijkstraAlgo(int graph[6][6],int src) // adjacency matrix


{
int distance[6]; // // array to calculate the minimum distance for each node
bool Tset[6];// boolean array to mark visited and unvisited for each node

for(int k = 0; k<6; k++)


{
distance[k] = INT_MAX;
Tset[k] = false;
}

distance[src] = 0; // Source vertex distance is set 0

for(int k = 0; k<6; k++)


{
int m=miniDist(distance,Tset);
Tset[m]=true;
for(int k = 0; k<6; k++)
{
// updating the distance of neighbouring vertex
if(!Tset[k] && graph[m][k] && distance[m]!=INT_MAX && distance[m]+graph[m]
[k]<distance[k])
distance[k]=distance[m]+graph[m][k];
}
}
cout<<"Vertex\t\tDistance from source vertex"<<endl;
for(int k = 0; k<6; k++)
{
char str=65+k;
cout<<str<<"\t\t\t"<<distance[k]<<endl;
}
}

int main()
{
int graph[6][6]={
{0, 1, 2, 0, 0, 0},
{1, 0, 0, 5, 1, 0},
{2, 0, 0, 2, 3, 0},
{0, 5, 2, 0, 2, 2},
{0, 1, 3, 2, 0, 1},
{0, 0, 0, 2, 1, 0}};
DijkstraAlgo(graph,0);
return 0;
}

Bellmen ford algorithm:

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

typedef struct edge


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

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


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

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


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

/* distance of source vertex from source vertex is o */


dis[src_graph]=0;

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


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

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


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

/* checking if negative cycle is present */


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

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


{
cout<<"\n\nNEGATIVE CYCLE PRESENT..!!\n";
return;
}
}
cout<<"\nVertex"<<" Distance from source";
for(i=1;i<=nv;i++)
{
cout<<"\n"<<i<<"\t"<<dis[i];
}

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

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


cin>>nv;

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

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


cin>>ne;

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

bellman_ford(nv,e,src_graph,ne);

return 0;
}

Implementation of Matrix Chain Multiplication.


#include<iostream>
#include<limits.h>

using namespace std;

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

int MatrixChainMultiplication(int p[], int n)


{
int m[n][n];
int i, j, k, L, q;

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


m[i][i] = 0; //number of multiplications are 0(zero) when there is only one matrix

//Here L is chain length. It varies from length 2 to length n.


for (L=2; L<n; L++)
{
for (i=1; i<n-L+1; i++)
{
j = i+L-1;
m[i][j] = INT_MAX; //assigning to maximum value

for (k=i; k<=j-1; k++)


{
q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];
if (q < m[i][j])
{
m[i][j] = q; //if number of multiplications found less that number will be
updated.
}
}
}
}

return m[1][n-1]; //returning the final answer which is M[1][n]

int main()
{
int n,i;
cout<<"Enter number of matrices\n";
cin>>n;

n++;

int arr[n];

cout<<"Enter dimensions \n";


for(i=0;i<n;i++)
{
cout<<"Enter d"<<i<<" :: ";
cin>>arr[i];
}

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

cout<<"Minimum number of multiplications is "<<MatrixChainMultiplication(arr, size));

return 0;
}

Activity Selection and Huffman Coding Implementation.


Activity Selection:
#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;
}
}
}

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

Huffman Coding:

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

// This constant can be avoided by explicitly


// calculating height of Huffman Tree
#define MAX_TREE_HT 100

// A Huffman tree node


struct MinHeapNode {

// One of the input characters


char data;

// Frequency of the character


unsigned freq;

// Left and right child of this node


struct MinHeapNode *left, *right;
};

// A Min Heap: Collection of


// min-heap (or Huffman tree) nodes
struct MinHeap {

// Current size of min heap


unsigned size;

// capacity of min heap


unsigned capacity;

// Array of minheap node pointers


struct MinHeapNode** array;
};

// A utility function allocate a new


// min heap node with given character
// and frequency of the character
struct MinHeapNode* newNode(char data, unsigned freq)
{
struct MinHeapNode* temp
= (struct MinHeapNode*)malloc
(sizeof(struct MinHeapNode));

temp->left = temp->right = NULL;


temp->data = data;
temp->freq = freq;
return temp;
}

// A utility function to create


// a min heap of given capacity
struct MinHeap* createMinHeap(unsigned capacity)

struct MinHeap* minHeap


= (struct MinHeap*)malloc(sizeof(struct MinHeap));

// current size is 0
minHeap->size = 0;

minHeap->capacity = capacity;

minHeap->array
= (struct MinHeapNode**)malloc(minHeap->
capacity * sizeof(struct MinHeapNode*));
return minHeap;
}

// A utility function to
// swap two min heap nodes
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{

struct MinHeapNode* t = *a;


*a = *b;
*b = t;
}

// The standard minHeapify function.


void minHeapify(struct MinHeap* minHeap, int idx)

int smallest = idx;


int left = 2 * idx + 1;
int right = 2 * idx + 2;

if (left < minHeap->size && minHeap->array[left]->


freq < minHeap->array[smallest]->freq)
smallest = left;
if (right < minHeap->size && minHeap->array[right]->
freq < minHeap->array[smallest]->freq)
smallest = right;

if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest],
&minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}

// A utility function to check


// if size of heap is 1 or not
int isSizeOne(struct MinHeap* minHeap)
{

return (minHeap->size == 1);


}

// A standard function to extract


// minimum value node from heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)

struct MinHeapNode* temp = minHeap->array[0];


minHeap->array[0]
= minHeap->array[minHeap->size - 1];

--minHeap->size;
minHeapify(minHeap, 0);

return temp;
}

// A utility function to insert


// a new node to Min Heap
void insertMinHeap(struct MinHeap* minHeap,
struct MinHeapNode* minHeapNode)

++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) {

minHeap->array[i] = minHeap->array[(i - 1) / 2];


i = (i - 1) / 2;
}

minHeap->array[i] = minHeapNode;
}

// A standard function to build min heap


void buildMinHeap(struct MinHeap* minHeap)

int n = minHeap->size - 1;
int i;

for (i = (n - 1) / 2; i >= 0; --i)


minHeapify(minHeap, i);
}

// A utility function to print an array of size n


void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
cout<< arr[i];

cout<<"\n";
}

// Utility function to check if this node is leaf


int isLeaf(struct MinHeapNode* root)

return !(root->left) && !(root->right);


}

// Creates a min heap of capacity


// equal to size and inserts all character of
// data[] in min heap. Initially size of
// min heap is equal to capacity
struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size)

{
struct MinHeap* minHeap = createMinHeap(size);

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


minHeap->array[i] = newNode(data[i], freq[i]);

minHeap->size = size;
buildMinHeap(minHeap);

return minHeap;
}

// The main function that builds Huffman tree


struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size)

{
struct MinHeapNode *left, *right, *top;

// Step 1: Create a min heap of capacity


// equal to size. Initially, there are
// modes equal to size.
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);

// Iterate while size of heap doesn't become 1


while (!isSizeOne(minHeap)) {

// Step 2: Extract the two minimum


// freq items from min heap
left = extractMin(minHeap);
right = extractMin(minHeap);

// Step 3: Create a new internal


// node with frequency equal to the
// sum of the two nodes frequencies.
// Make the two extracted node as
// left and right children of this new node.
// Add this node to the min heap
// '$' is a special value for internal nodes, not used
top = newNode('$', left->freq + right->freq);

top->left = left;
top->right = right;

insertMinHeap(minHeap, top);
}
// Step 4: The remaining node is the
// root node and the tree is complete.
return extractMin(minHeap);
}

// Prints huffman codes from the root of Huffman Tree.


// It uses arr[] to store codes
void printCodes(struct MinHeapNode* root, int arr[], int top)

// Assign 0 to left edge and recur


if (root->left) {

arr[top] = 0;
printCodes(root->left, arr, top + 1);
}

// Assign 1 to right edge and recur


if (root->right) {

arr[top] = 1;
printCodes(root->right, arr, top + 1);
}

// If this is a leaf node, then


// it contains one of the input
// characters, print the character
// and its code from arr[]
if (isLeaf(root)) {

cout<< root->data <<": ";


printArr(arr, top);
}
}

// The main function that builds a


// Huffman Tree and print codes by traversing
// the built Huffman Tree
void HuffmanCodes(char data[], int freq[], int size)

{
// Construct Huffman Tree
struct MinHeapNode* root
= buildHuffmanTree(data, freq, size);
// Print Huffman codes using
// the Huffman tree built above
int arr[MAX_TREE_HT], top = 0;

printCodes(root, arr, top);


}

// Driver code
int main()
{

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


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

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

HuffmanCodes(arr, freq, size);

return 0;
}

You might also like