DAA Final

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

ALIGARH COLLEGE OF ENGINEERING AND TECHNOLOGY,ALIGARH

(Approved By AICTE New Delhi, Affiliated to AKTU Lucknow)

PRACTICAL FILE
Submitted in partial fulfillment for the award of
BACHELOR OF TECHNOLOGY
(CSE), 3rd year
Submitted by
RUPESH VARSHNEY
Roll No:- 2001090100045

Submitted To
Mr. Dewang Chaudhary
(Design and Analysis of Algorithm Lab: KCS-553)
[Session: 2022-2023]
S.NO. NAME OF EXPERIMENT SIGNATURE

1. Searching Techniques- Linear & Binary


Search using Recursion method

2. Different Types Of Sorting- Insertion,


Selection,Heap,Quick , Merge

3. Knapsack Problem using Grady Problem

4. Travelling Salesman Problem

5. Minimum Spanning Tree using Kruskal’s


Algorithm

6. N-Queen Problem Using Backtracking

7. Dijkastra's Algorithm

8. Bellman Ford Algorithm

9. Prim's Algorithm

10. RB Tree - Insert & Delete

11. Binomial Heap

12. Matrix Chain Multiplication

13. Warshall's Algorithm

14. Graph Colouring

15. Hamiltonian Cycle

Name:- Rupesh Varshney

Practical Name:- Design and Analysis of Algorithm Lab

Practical Code:- KCS-553

Branch/Year:- CSE 3rd Year (5th Sem)

Class Roll No:- B-05

AKTU Roll No:- 2001090100045


1. Program for Recursive Linear Search.

#include <stdio.h>
int RecursiveLS(int arr[], int value, int index, int n)
{
int pos = 0;

if(index >= n)
{
return 0;
}

else if (arr[index] == value)


{
pos = index + 1;
return pos;
}

else
{
return RecursiveLS(arr, value, index+1, n);
}
return pos;
}

int main()
{
int n, value, pos, m = 0, arr[100];
printf("Enter the total elements in the array ");
scanf("%d", &n);

printf("Enter the array elements\n");


for (int i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}

printf("Enter the element to search ");


scanf("%d", &value);

pos = RecursiveLS(arr, value, 0, n);


if (pos != 0)
{
printf("Element found at pos %d ", pos);
}
else
{
printf("Element not found");
}
return 0;
}

2. Program for Recursive Binary Search.


#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x) return mid;
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
3. Heap Sort
#include <stdio.h>
void swap(int* a, int* b)
{

int temp = *a;

*a = *b;

*b = temp;
}
void heapify(int arr[], int N, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < N && arr[left] > arr[largest])

largest = left;
if (right < N && arr[right] > arr[largest])

largest = right;
if (largest != i) {

swap(&arr[i], &arr[largest]);
heapify(arr, N, largest);
}
}
void heapSort(int arr[], int N)
{
for (int i = N / 2 - 1; i >= 0; i--)

heapify(arr, N, i);
for (int i = N - 1; i >= 0; i--) {

swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
void printArray(int arr[], int N)
{
for (int i = 0; i < N; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) / sizeof(arr[0]);

// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
}

4. Merge Sort
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int l, int m, int r)


{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */


int L[n1], R[n2];

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


L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

void mergeSort(int arr[], int l, int r)


{
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}
5. Selection Sort
#include <stdio.h>
void selectionSort(int arr[], int size);
void swap(int *a, int *b);

void selectionSort(int arr[], int size)


{
int i, j;
for (i = 0 ; i < size;i++)
{
for (j = i ; j < size; j++)
{
if (arr[i] > arr[j])
swap(&arr[i], &arr[j]);
}
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int array[10], i, size;
printf("How many numbers you want to sort: ");
scanf("%d", &size);
printf("\nEnter %d numbers\t", size);
printf("\n");
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
selectionSort(array, size);
printf("\nSorted array is ");
for (i = 0; i < size;i++)
printf(" %d ", array[i]);
return 0;
}

6. Quick Sort
#include <stdio.h>
#include <stdlib.h>

int quickSort(int *arr, int low, int high)


{
int i = low, j = high;
int pivot = arr[(low + high) / 2];
while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(arr, low, j);
if (i < high)
quickSort(arr, i, high);
return 0;
}
int main(void)
{
puts("Enter the number of elements in the array: ");
int n;
scanf("%d", &n);
int arr[n];
puts("Enter the elements of the array: ");
for (int i = 0; i < n; i++)
{
printf("arr[%d]: ", i);
scanf("%d", &arr[i]);
}
int low = 0;
int high = n - 1;
int pivot = arr[high];
int k = low - 1;
for (int j = low; j < high; j++)
{
if (arr[j] <= pivot)
{
k++;
int temp = arr[k];
arr[k] = arr[j];
arr[j] = temp;
}
}
int temp = arr[k + 1];
arr[k + 1] = arr[high];
arr[high] = temp;
int pi = k + 1;
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
puts("The sorted array is: ");
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
7. Insertion Sort
#include <stdio.h>
int main(void)
{
int n, i, j, temp;
int arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i < n; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i < n; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
8. Knapsack Problem using Grady Problem
# include<stdio.h>

void knapsack(int n, float weight[], float profit[], float capacity) {


float x[20], tp = 0;
int i, j, u;
u = capacity;

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


x[i] = 0.0;

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


if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}

if (i < n)
x[i] = u / weight[i];

tp = tp + (x[i] * profit[i]);

printf("\nThe result vector is:- ");


for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);

int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;

printf("\nEnter the no. of objects:- ");


scanf("%d", &num);

printf("\nEnter the wts and profits of each object:- ");


for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}

printf("\nEnter the capacityacity of knapsack:- ");


scanf("%f", &capacity);

for (i = 0; i < num; i++) {


ratio[i] = profit[i] / weight[i];
}

for (i = 0; i < num; i++) {


for (j = i + 1; j < num; j++) {
if (ratio[i] < ratio[j]) {
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;

temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}

knapsack(num, weight, profit, capacity);


return(0);
}
9. Travelling Salesman Problem

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

int travellingSalesmanProblem(int graph[][V], int s)


{
vector<int> vertex;
for (int i = 0; i < V; i++)
if (i != s)
vertex.push_back(i);
int min_path = INT_MAX;
do {
int current_pathweight = 0;

int k = s;
for (int i = 0; i <vertex.size(); i++) {
current_pathweight += graph[k][vertex[i]];
k = vertex[i];
}
current_pathweight += graph[k][s];

min_path = min(min_path, current_pathweight);

} while (
next_permutation(vertex.begin(), vertex.end()));

return min_path;
}

// Driver Code
int main()
{
int graph[][V] = { { 0, 10, 15, 20 },
{ 10, 0, 35, 25 },
{ 15, 35, 0, 30 },
{ 20, 25, 30, 0 } };
int s = 0;
cout << travellingSalesmanProblem(graph, s) << endl;
return 0;
}

10. Minimum Spanning Tree using Kruskal’s Algorithm


#include <bits/stdc++.h>
using namespace std;
class DSU {
int* parent;
int* rank;

public:
DSU(int n)
{
parent = new int[n];
rank = new int[n];

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


parent[i] = -1;
rank[i] = 1;
}
}

int find(int i)
{
if (parent[i] == -1)
return i;

return parent[i] = find(parent[i]);


}

// Union function
void unite(int x, int y)
{
int s1 = find(x);
int s2 = find(y);

if (s1 != s2) {
if (rank[s1] < rank[s2]) {
parent[s1] = s2;
rank[s2] += rank[s1];
}
else {
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
};

class Graph {
vector<vector<int> > edgelist;
int V;

public:
Graph(int V) { this->V = V; }

void addEdge(int x, int y, int w)


{
edgelist.push_back({ w, x, y });
}

void kruskals_mst()
{
// 1. Sort all edges
sort(edgelist.begin(), edgelist.end());

// Initialize the DSU


DSU s(V);
int ans = 0;
cout << "Following are the edges in the "
"constructed MST"
<< endl;
for (auto edge : edgelist) {
int w = edge[0];
int x = edge[1];
int y = edge[2];

// Take this edge in MST if it does


// not forms a cycle
if (s.find(x) != s.find(y)) {
s.unite(x, y);
ans += w;
cout << x << " -- " << y << " == " << w
<< endl;
}
}

cout << "Minimum Cost Spanning Tree: " << ans;


}
};

int main()
{
Graph g(4);
g.addEdge(0, 1, 10);
g.addEdge(1, 3, 15);
g.addEdge(2, 3, 4);
g.addEdge(2, 0, 6);
g.addEdge(0, 3, 5);
g.kruskals_mst();
return 0;
}

11. N Queen Problem Using Backtracking

#include<stdio.h>
#include<math.h>

int board[20],count;

int main()
{
int n,i,j;
void queen(int row,int n);
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);

for(i=1;i<=n;++i)
printf("\t%d",i);

for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}

return 1;
}

void queen(int row,int n)


{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}
}

12. Dijkastra's Algorithm

#include <limits.h>
#include <stdbool.h>
#include <stdio.h>

#define V 9
int minDistance(int dist[], bool sptSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

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


if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;

return min_index;
}
void printSolution(int dist[])
{
printf("Vertex \t\t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t\t\t\t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;

// Distance of source vertex from itself is always 0


dist[src] = 0;

// Find shortest path for all vertices


for (int count = 0; count < V - 1; count++) {
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v]&& dist[u] != INT_MAX&& dist[u] + graph[u][v] <
dist[v])
dist[v] = dist[u] + graph[u][v];
}

printSolution(dist);
}

// driver's code
int main()
{
/* Let us create the example graph discussed above */
int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
dijkstra(graph, 0);

return 0;
}
13. 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)
{
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;
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; // If negative cycle is detected, simply
// return
}
}

printArr(dist, V);

return;
}
int main()
{
int V = 5; // Number of vertices in graph
int E = 8; // Number of edges in graph
struct Graph* graph = createGraph(V, E);
graph->edge[0].src = 0;
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;
}

14. Prim's Algorithm


#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 5
int minKey(int key[], bool mstSet[])
{
// Initialize min value
int min = INT_MAX, min_index;

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


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}

int printMST(int parent[], int graph[V][V])


{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i,
graph[i][parent[i]]);
}
void primMST(int graph[V][V])
{
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] =false;
key[0] = 0;
parent[0] = -1; // First node is always root of MST
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false&& graph[u][v] < key[v])parent[v] = u,
key[v] = graph[u][v];
}

// print the constructed MST


printMST(parent, graph);
}
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };

// Print the solution


primMST(graph);

return 0;
}
15. RB Tree - Insert & Delete
#include <stdio.h>
#include <stdlib.h>

enum nodeColor {
RED,
BLACK
};

struct rbNode {
int data, colour;
struct rbNode *link[2];
};

struct rbNode *root = NULL;


struct rbNode *createNode(int data) {
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->colour = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}
void insertion(int data) {
struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;
int dir[98], ht = 0, index;
ptr = root;
if (!root) {
root = createNode(data);
return;
}

stack[ht] = root;
dir[ht++] = 0;
while (ptr != NULL) {
if (ptr->data == data) {
printf("Duplicates Not Allowed!!\n");
return;
}
index = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
ptr = ptr->link[index];
dir[ht++] = index;
}
stack[ht - 1]->link[index] = newnode = createNode(data);
while ((ht >= 3) && (stack[ht - 1]->colour == RED)) {
if (dir[ht - 2] == 0) {
yPtr = stack[ht - 2]->link[1];
if (yPtr != NULL && yPtr->colour == RED) {
stack[ht - 2]->colour = RED;
stack[ht - 1]->colour = yPtr->colour = BLACK;
ht = ht - 2;
} else {
if (dir[ht - 1] == 0) {
yPtr = stack[ht - 1];
} else {
xPtr = stack[ht - 1];
yPtr = xPtr->link[1];
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
stack[ht - 2]->link[0] = yPtr;
}
xPtr = stack[ht - 2];
xPtr->colour = RED;
yPtr->colour = BLACK;
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
if (xPtr == root) {
root = yPtr;
} else {
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
} else {
yPtr = stack[ht - 2]->link[0];
if ((yPtr != NULL) && (yPtr->colour == RED)) {
stack[ht - 2]->colour = RED;
stack[ht - 1]->colour = yPtr->colour = BLACK;
ht = ht - 2;
} else {
if (dir[ht - 1] == 1) {
yPtr = stack[ht - 1];
} else {
xPtr = stack[ht - 1];
yPtr = xPtr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
stack[ht - 2]->link[1] = yPtr;
}
xPtr = stack[ht - 2];
yPtr->colour = BLACK;
xPtr->colour = RED;
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
if (xPtr == root) {
root = yPtr;
} else {
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
}
root->colour = BLACK;
}

// Delete a node
void deletion(int data) {
struct rbNode *stack[98], *ptr, *xPtr, *yPtr;
struct rbNode *pPtr, *qPtr, *rPtr;
int dir[98], ht = 0, diff, i;
enum nodeColor colour;

if (!root) {
printf("Tree not available\n");
return;
}

ptr = root;
while (ptr != NULL) {
if ((data - ptr->data) == 0)
break;
diff = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
dir[ht++] = diff;
ptr = ptr->link[diff];
}

if (ptr->link[1] == NULL) {
if ((ptr == root) && (ptr->link[0] == NULL)) {
free(ptr);
root = NULL;
} else if (ptr == root) {
root = ptr->link[0];
free(ptr);
} else {
stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];
}
} else {
xPtr = ptr->link[1];
if (xPtr->link[0] == NULL) {
xPtr->link[0] = ptr->link[0];
colour = xPtr->colour;
xPtr->colour = ptr->colour;
ptr->colour = colour;

if (ptr == root) {
root = xPtr;
} else {
stack[ht - 1]->link[dir[ht - 1]] = xPtr;
}

dir[ht] = 1;
stack[ht++] = xPtr;
} else {
i = ht++;
while (1) {
dir[ht] = 0;
stack[ht++] = xPtr;
yPtr = xPtr->link[0];
if (!yPtr->link[0])
break;
xPtr = yPtr;
}

dir[i] = 1;
stack[i] = yPtr;
if (i > 0)
stack[i - 1]->link[dir[i - 1]] = yPtr;

yPtr->link[0] = ptr->link[0];

xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = ptr->link[1];

if (ptr == root) {
root = yPtr;
}

colour = yPtr->colour;
yPtr->colour = ptr->colour;
ptr->colour = colour;
}
}

if (ht < 1)
return;

if (ptr->colour == BLACK) {
while (1) {
pPtr = stack[ht - 1]->link[dir[ht - 1]];
if (pPtr && pPtr->colour == RED) {
pPtr->colour = BLACK;
break;
}

if (ht < 2)
break;

if (dir[ht - 2] == 0) {
rPtr = stack[ht - 1]->link[1];

if (!rPtr)
break;

if (rPtr->colour == RED) {
stack[ht - 1]->colour = RED;
rPtr->colour = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];

if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 0;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;

rPtr = stack[ht - 1]->link[1];


}

if ((!rPtr->link[0] || rPtr->link[0]->colour == BLACK) &&


(!rPtr->link[1] || rPtr->link[1]->colour == BLACK)) {
rPtr->colour = RED;
} else {
if (!rPtr->link[1] || rPtr->link[1]->colour == BLACK) {
qPtr = rPtr->link[0];
rPtr->colour = RED;
qPtr->colour = BLACK;
rPtr->link[0] = qPtr->link[1];
qPtr->link[1] = rPtr;
rPtr = stack[ht - 1]->link[1] = qPtr;
}
rPtr->colour = stack[ht - 1]->colour;
stack[ht - 1]->colour = BLACK;
rPtr->link[1]->colour = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
} else {
rPtr = stack[ht - 1]->link[0];
if (!rPtr)
break;

if (rPtr->colour == RED) {
stack[ht - 1]->colour = RED;
rPtr->colour = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];

if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 1;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;

rPtr = stack[ht - 1]->link[0];


}
if ((!rPtr->link[0] || rPtr->link[0]->colour == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->colour == BLACK)) {
rPtr->colour = RED;
} else {
if (!rPtr->link[0] || rPtr->link[0]->colour == BLACK) {
qPtr = rPtr->link[1];
rPtr->colour = RED;
qPtr->colour = BLACK;
rPtr->link[1] = qPtr->link[0];
qPtr->link[0] = rPtr;
rPtr = stack[ht - 1]->link[0] = qPtr;
}
rPtr->colour = stack[ht - 1]->colour;
stack[ht - 1]->colour = BLACK;
rPtr->link[0]->colour = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
ht--;
}
}
}
void inorderTraversal(struct rbNode *node) {
if (node) {
inorderTraversal(node->link[0]);
printf("%d ", node->data);
inorderTraversal(node->link[1]);
}
return;
}

// Driver code
int main() {
int ch, data;
while (1) {
printf("1. Insertion\t2. Deletion\n");
printf("3. Traverse\t4. Exit");
printf("\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the element to insert:");
scanf("%d", &data);
insertion(data);
break;
case 2:
printf("Enter the element to delete:");
scanf("%d", &data);
deletion(data);
break;
case 3:
inorderTraversal(root);
printf("\n");
break;
case 4:
exit(0);
default:
printf("Not available\n");
break;
}
printf("\n");
}
return 0;
}

16. Binomial Heap

#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data, degree;
Node *child, *sibling, *parent;
};

Node* newNode(int key)


{
Node *temp = new Node;
temp->data = key;
temp->degree = 0;
temp->child = temp->parent = temp->sibling = NULL;
return temp;
}
Node* mergeBinomialTrees(Node *b1, Node *b2)
{
// Make sure b1 is smaller
if (b1->data > b2->data)
swap(b1, b2);
b2->parent = b1;
b2->sibling = b1->child;
b1->child = b2;
b1->degree++;
return b1;
}
list<Node*> unionBionomialHeap(list<Node*> l1,
list<Node*> l2)
{
list<Node*> _new;
list<Node*>::iterator it = l1.begin();
list<Node*>::iterator ot = l2.begin();
while (it!=l1.end() && ot!=l2.end())
{
if((*it)->degree <= (*ot)->degree)
{
_new.push_back(*it);
it++;
}
else
{
_new.push_back(*ot);
ot++;
}
}
while (it != l1.end())
{
_new.push_back(*it);
it++;
}
while (ot!=l2.end())
{
_new.push_back(*ot);
ot++;
}
return _new;
}

list<Node*> adjust(list<Node*> _heap)


{
if (_heap.size() <= 1)
return _heap;
list<Node*> new_heap;
list<Node*>::iterator it1,it2,it3;
it1 = it2 = it3 = _heap.begin();

if (_heap.size() == 2)
{
it2 = it1;
it2++;
it3 = _heap.end();
}
else
{
it2++;
it3=it2;
it3++;
}
while (it1 != _heap.end())
{
if (it2 == _heap.end())
it1++;

{
it1++;
it2++;
if(it3!=_heap.end())
it3++;
}

else if (it3!=_heap.end() &&


(*it1)->degree == (*it2)->degree &&
(*it1)->degree == (*it3)->degree)
{
it1++;
it2++;
it3++;
}
else if ((*it1)->degree == (*it2)->degree)
{
Node *temp;
*it1 = mergeBinomialTrees(*it1,*it2);
it2 = _heap.erase(it2);
if(it3 != _heap.end())
it3++;
}
}
return _heap;
}

// inserting a Binomial Tree into binomial heap


list<Node*> insertATreeInHeap(list<Node*> _heap,
Node *tree)
{
temp = unionBionomialHeap(_heap,temp);

return adjust(temp);
}
list<Node*> removeMinFromTreeReturnBHeap(Node *tree)
{
list<Node*> heap;
Node *temp = tree->child;
Node *lo;

// making a binomial heap from Binomial Tree


while (temp)
{
lo = temp;
temp = temp->sibling;
lo->sibling = NULL;
heap.push_front(lo);
}
return heap;
}
list<Node*> insert(list<Node*> _head, int key)
{
Node *temp = newNode(key);
return insertATreeInHeap(_head,temp);
}

// return pointer of minimum value Node


// present in the binomial heap
Node* getMin(list<Node*> _heap)
{
list<Node*>::iterator it = _heap.begin();
Node *temp = *it;
while (it != _heap.end())
{
if ((*it)->data < temp->data)
temp = *it;
it++;
}
return temp;
}

list<Node*> extractMin(list<Node*> _heap)


{
list<Node*> new_heap,lo;
Node *temp;

// temp contains the pointer of minimum value


// element in heap
temp = getMin(_heap);
list<Node*>::iterator it;
it = _heap.begin();
while (it != _heap.end())
{
if (*it != temp)
{
// inserting all Binomial Tree into new
// binomial heap except the Binomial Tree
// contains minimum element
new_heap.push_back(*it);
}
it++;
}
lo = removeMinFromTreeReturnBHeap(temp);
new_heap = unionBionomialHeap(new_heap,lo);
new_heap = adjust(new_heap);
return new_heap;
}

// print function for Binomial Tree


void printTree(Node *h)
{
while (h)
{
cout << h->data << " ";
printTree(h->child);
h = h->sibling;
}
}

// print function for binomial heap


void printHeap(list<Node*> _heap)
{
list<Node*> ::iterator it;
it = _heap.begin();
while (it != _heap.end())
{
printTree(*it);
it++;
}
}

// Driver program to test above functions


int main()
{
int ch,key;
list<Node*> _heap;

// Insert data in the heap


_heap = insert(_heap,10);
_heap = insert(_heap,20);
_heap = insert(_heap,30);

cout << "Heap elements after insertion:\n";


printHeap(_heap);

Node *temp = getMin(_heap);


cout << "\nMinimum element of heap "
<< temp->data << "\n";

// Delete minimum element of heap


_heap = extractMin(_heap);
cout << "Heap after deletion of minimum element\n";
printHeap(_heap);

return 0;
}

17. Matrix Chain Multiplication


#include <stdio.h>
int MatrixChainMultuplication(int arr[], int n) {
int minMul[n][n];
int j, q;
for (int i = 1; i < n; i++)
minMul[i][i] = 0;
for (int L = 2; L < n; L++) {
for (int i = 1; i < n - L + 1; i++) {
j = i + L - 1;
minMul[i][j] = 99999999;
for (int k = i; k <= j - 1; k++) {
q = minMul[i][k] + minMul[k + 1][j] + arr[i - 1] * arr[k] * arr[j];
if (q < minMul[i][j])
minMul[i][j] = q;
}
}
}
return minMul[1][n - 1];
}
int main(){
int arr[] = {3, 4, 5, 6, 7, 8};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Minimum number of multiplications required for the matrices multiplication is %d ",
MatrixChainMultuplication(arr, size));
getchar();
return 0;
}

18. Warshall's Algorithm


void printSolution(int dist[][V]);

// S
void floydWarshall(int graph[][V])
{ int dist[V][V], i, j, k;

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


for (j = 0; j < V; j++)
dist[i][j] = graph[i][j];
for (k = 0; k < V; k++) {

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


for (j = 0; j < V; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
printSolution();
}
void printSolution(int dist[][V])
{
printf("The following matrix shows the shortest distances between every pair of
vertices \n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
if (dist[i][j] == INF)
printf("%7s", "INF");
else
printf("%7d", dist[i][j]);
}
printf("\n");
}
}
int main()
{
int graph[V][V] = { { 0, 5, INF, 10 },
{ INF, 0, 3, INF },
{ INF, INF, 0, 1 },
{ INF, INF, INF, 0 } };

// Function call
floydWarshall(graph);
return 0;
}

19. Graph Colouring

#include<iostream>
#define NODE 6
using namespace std;

int graph[NODE][NODE] = {
{0, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 1, 0},
{1, 0, 0, 1, 0, 1},
{1, 1, 1, 0, 1, 1},
{0, 1, 0, 1, 0, 1},
{0, 0, 1, 1, 1, 0}
};

void graphColoring() {
int color[NODE];
color[0] = 0; //Assign first color for the first node
bool colorUsed[NODE]; //Used to check whether color is used or not

for(int i = 1; i<NODE; i++)


color[i] = -1; //initialize all other vertices are unassigned

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


colorUsed[i] = false; //initially any colors are not chosen

for(int u = 1; u<NODE; u++) { //for all other NODE - 1 vertices


for(int v = 0; v<NODE; v++) {
if(graph[u][v]){
if(color[v] != -1) //when one color is assigned, make it unavailable
colorUsed[color[v]] = true;
}
}

int col;
for(col = 0; col<NODE; col++)
if(!colorUsed[col]) //find a color which is not assigned
break;

color[u] = col; //assign found color in the list

for(int v = 0; v<NODE; v++) { //for next iteration make color availability to false
if(graph[u][v]) {
if(color[v] != -1)
colorUsed[color[v]] = false;
}
}
}

for(int u = 0; u<NODE; u++)


cout <<"Color: " << u << ", Assigned with Color: " <<color[u] <<endl;
}

main() {
graphColoring();
}
20. Hamiltonian Cycle

#include<stdio.h>
#define V 5

void printSolution(int path[]);


bool isSafe(int v, bool graph[V][V], int path[], int pos)
{
if (graph [ path[pos-1] ][ v ] == 0)
return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;

return true;
}
bool hamCycleUtil(bool graph[V][V], int path[], int pos)
{
if (pos == V)
{
if ( graph[ path[pos-1] ][ path[0] ] == 1 )
return true;
else
return false;
}
for (int v = 1; v < V; v++)
{
if (isSafe(v, graph, path, pos))
{
path[pos] = v;

/* recur to construct rest of the path */


if (hamCycleUtil (graph, path, pos+1) == true)
return true;

/* If adding vertex v doesn't lead to a solution,


then remove it */
path[pos] = -1;
}
}

/* If no vertex can be added to Hamiltonian Cycle constructed so far,


then return false */
return false;
}

bool hamCycle(bool graph[V][V])


{
int *path = new int[V];
for (int i = 0; i < V; i++)
path[i] = -1;
path[0] = 0;
if ( hamCycleUtil(graph, path, 1) == false )
{
printf("\nSolution does not exist");
return false;
}

printSolution(path);
return true;
}
void printSolution(int path[])
{
printf ("Solution Exists:"
" Following is one Hamiltonian Cycle \n");
for (int i = 0; i < V; i++)
printf(" %d ", path[i]);

// Let us print the first vertex again to show the complete cycle
printf(" %d ", path[0]);
printf("\n");
}

int main()
{
/* Let us create the following graph
(0)--(1)--(2)
|/\|
|/\|
|/ \|
(3)-------(4) */
bool graph1[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};

// Print the solution


hamCycle(graph1);

/* Let us create the following graph


(0)--(1)--(2)
|/\|
|/\|
|/ \|
(3) (4) */
bool graph2[V][V] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};

hamCycle(graph2);

return 0;
}

You might also like