0% found this document useful (0 votes)
8 views31 pages

ADA LabManual Aayush

Uploaded by

pbhavy15
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)
8 views31 pages

ADA LabManual Aayush

Uploaded by

pbhavy15
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/ 31

Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 1
Aim: Implementation and Time analysis of sorting algorithms.Bubble sort,
Selection sort, Insertion sort, Merge sort and Quicksort

INPUT:
#include <stdio.h>
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
// Bubble Sort
void bubbleSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Selection Sort
void selectionSort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min_idx = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min_idx])
{
min_idx = j;
}
}

BMCET, SURAT 1
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

int temp = arr[min_idx];


arr[min_idx] = arr[i];
arr[i] = temp;
}
}

// Insertion Sort
void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// Merge Sort Helper Functions
void merge(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (int i = 0; i < n1; i++)
L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}

BMCET, SURAT 2
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

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);
}
}
// Quicksort Helper Functions
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (arr[j] < pivot)
{
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;

BMCET, SURAT 3
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

}
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);

// printf("Bubble Sort: \n");


// bubbleSort(arr, n);

printf("Selection Sort: \n");


selectionSort(arr, n);

// printf("Insertion Sort: \n");


// insertionSort(arr, n);

// printf("Merge Sort: \n");


// mergeSort(arr, 0, n - 1);

// printf("Quick Sort: \n");


// quickSort(arr, 0, n - 1);

// printf("Sorted array: \n");

printArray(arr, n);
return 0;
}

BMCET, SURAT 4
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

OUTPUT:
Bubble Sort

Selection Sort

Insertion Sort

Merge Sort

Quick Sort

BMCET, SURAT 5
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 2
Aim: Implementation and Time analysis of linear and binary search algorithm

INPUT:
#include <stdio.h>
// Linear search function
int linearSearch(int arr[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == x)
{
return i;
}
}
return -1;
}
// Binary search function (iterative version)
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r)
{
int mid = l + (r - l) / 2;
if (arr[mid] == x)
{
return mid;
}
if (arr[mid] > x)
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
return -1;
}
int main()
{
int arr[] = {11, 12, 13, 14, 15, 16, 17};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 14;

BMCET, SURAT 6
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

// Linear search
int result1 = linearSearch(arr, n, x);
if (result1 != -1)
{
printf("Linear Search: Element found at index %d\n", result1);
}
else
{
printf("Linear Search: Element not found\n");
}
// Binary search (array must be sorted)
int result2 = binarySearch(arr, 0, n - 1, x);
if (result2 != -1)
{
printf("Binary Search: Element found at index %d\n", result2);
}
else
{
printf("Binary Search: Element not found\n");
}
return 0;
}

OUTPUT:

BMCET, SURAT 7
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 3
Aim: Implementation of max-heap sort algorithm.

INPUT:
#include <stdio.h>
// Function to swap two elements
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Function to heapify a subtree rooted at node i
// n is the size of the heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // Left child
int right = 2 * i + 2; // Right child
// If the left child is larger than the root
if (left < n && arr[left] > arr[largest])
{
largest = left;
}
// If the right child is larger than the largest so far
if (right < n && arr[right] > arr[largest])
{
largest = right;
}
// If the largest is not the root
if (largest != i)
{
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected subtree
heapify(arr, n, largest);
}
}
// Function to perform heap sort
void heapSort(int arr[], int n)
{
// Build a max-heap
for (int i = n / 2 - 1; i >= 0; i--)
{

BMCET, SURAT 8
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

heapify(arr, n, i);
}
// One by one extract elements from the heap
for (int i = n - 1; i > 0; i--)
{
// Move current root to end
swap(&arr[0], &arr[i]);
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Function to print the array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int arr[] = {10, 9, 8, 3, 2, 7};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
heapSort(arr, n);
printf("Sorted array using heap sort: \n");
printArray(arr, n);
return 0;
}

OUTPUT:

BMCET, SURAT 9
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 4
Aim: Implementation and Time analysis of factorial programs using iterative
and recursive methods.

INPUT:
#include <stdio.h>
// Iterative function to calculate factorial
int factorialIterative(int n)
{
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
}
return result;
}
// Recursive function to calculate factorial
int factorialRecursive(int n)
{
if (n == 0 || n == 1)
{
return 1; // Base case
}
return n * factorialRecursive(n - 1); // Recursive case
}
int main()
{
int num = 5;
// Iterative method
printf("Factorial of %d (Iterative) is: %d\n", num, factorialIterative(num));
// Recursive method
printf("Factorial of %d (Recursive) is: %d\n", num, factorialRecursive(num));
return 0;
}

OUTPUT:

BMCET, SURAT 10
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 5
Aim: Implementation of a knapsack problem using dynamic programming.

INPUT:
#include <stdio.h>
// Function to return the maximum of two integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Function to solve 0/1 Knapsack Problem using dynamic programming
int knapsack(int W, int wt[], int val[], int n)
{
int i, w;
int dp[n + 1][W + 1]; // DP table to store maximum values for subproblems
// Build table dp[][] in bottom-up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
{
dp[i][w] = 0; // Base case: no items or no capacity
}
else if (wt[i - 1] <= w)
{
// Max of: Including the item or excluding the item
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]], dp[i - 1][w]);
}
else
{
dp[i][w] = dp[i - 1][w]; // Exclude the item
}
}
}
return dp[n][W]; // The result is stored in dp[n][W]
}
int main()
{
int val[] = {60, 100, 120}; // Values of items
int wt[] = {10, 20, 30}; // Weights of items
int W = 50; // Capacity of knapsack
int n = sizeof(val) / sizeof(val[0]); // Number of items

BMCET, SURAT 11
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

int max_value = knapsack(W, wt, val, n); // Solve the knapsack problem
printf("Maximum value in knapsack of capacity %d is: %d\n", W, max_value);
return 0;
}

OUTPUT:

BMCET, SURAT 12
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 6
Aim: Implementation of chain matrix multiplication using dynamic
programming

INPUT:
#include <stdio.h>
#include <limits.h>
// Function to find the minimum number of multiplications
int matrixChainOrder(int p[], int n)
{
// m[i][j] will hold the minimum number of multiplications
int m[n][n];
// Initialize the diagonal of the matrix to zero
for (int i = 1; i < n; i++)
{
m[i][i] = 0;
}
// l is the chain length
for (int l = 2; l < n; l++)
{
for (int i = 1; i < n - l + 1; i++)
{
int j = i + l - 1;
m[i][j] = INT_MAX; // Initialize to a large value
// Try placing the parenthesis at different positions and find the minimum
for (int k = i; k < j; k++)
{
// q = cost/scalar multiplications
int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < m[i][j])
{
m[i][j] = q;
}
}
}
}
return m[1][n - 1]; // Return the minimum cost for matrices from 1 to n-1
}
int main()
{
int arr[] = {40, 45, 25, 15, 30, 35, 5};
int size = sizeof(arr) / sizeof(arr[0]);
// Call the matrixChainOrder function

BMCET, SURAT 13
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

int minMultiplications = matrixChainOrder(arr, size);


// Print the result
printf("Minimum number of multiplications is: %d\n", minMultiplications);
return 0;
}

OUTPUT:

BMCET, SURAT 14
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 7
Aim: Implementation of making a change problem using dynamic
programming

INPUT:
#include <stdio.h>
#include <limits.h> // For INT_MAX
// Function to find the minimum number of coins required to make change
int minCoins(int coins[], int n, int amount)
{
// Create a table to store the minimum number of coins for each amount from 0 to amount
int dp[amount + 1];
// Initialize dp array with a large value
for (int i = 0; i <= amount; i++)
{
dp[i] = INT_MAX;
}
// Base case: No coins are needed to make 0 amount
dp[0] = 0;
// Fill the dp array in a bottom-up manner
for (int i = 1; i <= amount; i++)
{
for (int j = 0; j < n; j++)
{
if (coins[j] <= i)
{
int sub_res = dp[i - coins[j]];
if (sub_res != INT_MAX && sub_res + 1 < dp[i])
{
dp[i] = sub_res + 1;
}
}
}
}
// Return the result, if no solution is found, return -1
return dp[amount] == INT_MAX ? -1 : dp[amount];
}
int main()
{
int coins[] = {1, 2, 5}; // Coin denominations
int n = sizeof(coins) / sizeof(coins[0]);
int amount = 11; // Total amount for which change is to be made
// Call the minCoins function

BMCET, SURAT 15
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

int result = minCoins(coins, n, amount);


if (result == -1)
{
printf("It is not possible to make the amount %d with the given coins.\n", amount);
}
else
{
printf("Minimum number of coins required to make amount %d is: %d\n", amount,
result);
}
return 0;
}

OUTPUT:

BMCET, SURAT 16
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 8
Aim: Implementation of a knapsack problem using greedy algorithms.

INPUT:
#include <stdio.h>
// Structure for an item which stores weight and corresponding value
struct Item
{
int value;
int weight;
};
// Function to swap two items
void swap(struct Item *a, struct Item *b)
{
struct Item temp = *a;
*a = *b;
*b = temp;
}
// Function to sort items according to value/weight ratio in descending order
void sortItems(struct Item items[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
double r1 = (double)items[j].value / items[j].weight;
double r2 = (double)items[j + 1].value / items[j + 1].weight;
if (r1 < r2)
{
swap(&items[j], &items[j + 1]);
}
}
}
}
// Function to calculate maximum value we can obtain
double fractionalKnapsack(int W, struct Item items[], int n)
{
// Sort items by value/weight ratio
sortItems(items, n);
double totalValue = 0.0; // Total value in the knapsack
// Loop through the sorted items
for (int i = 0; i < n; i++)
{

BMCET, SURAT 17
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

// If the item can fit in the knapsack, take it completely


if (items[i].weight <= W)
{
W -= items[i].weight;
totalValue += items[i].value;
}
// Otherwise, take the fraction of the item that fits
else
{
totalValue += items[i].value * ((double)W / items[i].weight);
break; // Since the knapsack is full now, break the loop
}
}
return totalValue; // Return the maximum value we can achieve
}
int main()
{
int W = 50; // Capacity of the knapsack
struct Item items[] = {{70, 20}, {110, 30}, {130, 40}}; // Array of items with {value,
weight}
int n = sizeof(items) / sizeof(items[0]); // Number of items
// Call the fractionalKnapsack function
double maxValue = fractionalKnapsack(W, items, n);
// Print the maximum value
printf("Maximum value we can obtain = %.2f\n", maxValue);
return 0;
}

OUTPUT:

BMCET, SURAT 18
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 9
Aim: Implementation of Graph and Searching (DFS and BFS)

INPUT:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Define a node for the adjacency list
typedef struct Node
{
int data;
struct Node *next;
} Node;
// Define the Graph structure
typedef struct Graph
{
int numVertices;
Node **adjLists;
} Graph;
// Function to create a new adjacency list node
Node *createNode(int data)
{
Node *newNode = malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to create a graph with `numVertices` vertices
Graph *createGraph(int numVertices)
{
Graph *graph = malloc(sizeof(Graph));
graph->numVertices = numVertices;
graph->adjLists = malloc(numVertices * sizeof(Node *));
for (int i = 0; i < numVertices; i++)
{
graph->adjLists[i] = NULL;
}
return graph;
}
// Function to add an edge to the graph
void addEdge(Graph *graph, int src, int dest)
{
// Add an edge from src to dest

BMCET, SURAT 19
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Node *newNode = createNode(dest);


newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Since it's an undirected graph, add an edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// Function to print the adjacency list representation of the graph
void printGraph(Graph *graph)
{
for (int i = 0; i < graph->numVertices; i++)
{
Node *temp = graph->adjLists[i];
printf("Vertex %d: ", i);
while (temp)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
}
// Depth-First Search (DFS) algorithm
void DFSUtil(Graph *graph, int vertex, bool *visited)
{
// Mark the current node as visited and print it
visited[vertex] = true;
printf("%d ", vertex);
// Recur for all the vertices adjacent to this vertex
Node *temp = graph->adjLists[vertex];
while (temp)
{
int adjVertex = temp->data;
if (!visited[adjVertex])
{
DFSUtil(graph, adjVertex, visited);
}
temp = temp->next;
}
}
void DFS(Graph *graph, int startVertex)
{
// Mark all the vertices as not visited

BMCET, SURAT 20
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

bool *visited = malloc(graph->numVertices * sizeof(bool));


for (int i = 0; i < graph->numVertices; i++)
{
visited[i] = false;
}
// Call the recursive helper function to print DFS traversal
DFSUtil(graph, startVertex, visited);
// Free the visited array
free(visited);
}
// Breadth-First Search (BFS) algorithm
void BFS(Graph *graph, int startVertex)
{
// Mark all the vertices as not visited
bool *visited = malloc(graph->numVertices * sizeof(bool));
for (int i = 0; i < graph->numVertices; i++)
{
visited[i] = false;
}
// Create a queue for BFS
int *queue = malloc(graph->numVertices * sizeof(int));
int front = 0;
int rear = 0;
// Mark the start vertex as visited and enqueue it
visited[startVertex] = true;
queue[rear++] = startVertex;
while (front < rear)
{
// Dequeue a vertex from queue and print it
int vertex = queue[front++];
printf("%d ", vertex);
// Get all adjacent vertices of the dequeued vertex
Node *temp = graph->adjLists[vertex];
while (temp)
{
int adjVertex = temp->data;
if (!visited[adjVertex])
{
visited[adjVertex] = true;
queue[rear++] = adjVertex;
}
temp = temp->next;
}
}

BMCET, SURAT 21
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

// Free the visited array and queue


free(visited);
free(queue);
}
int main()
{
// Create a graph and add edges
Graph *graph = createGraph(5);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
addEdge(graph, 4, 0);
addEdge(graph, 4, 1);
// Print the adjacency list representation of the graph
printGraph(graph);
printf("DFS starting from vertex 0:\n");
DFS(graph, 0);
printf("\nBFS starting from vertex 0:\n");
BFS(graph, 0);
// Free the graph
for (int i = 0; i < graph->numVertices; i++)
{
Node *temp = graph->adjLists[i];
while (temp)
{
Node *prev = temp;
temp = temp->next;
free(prev);
}
}
free(graph->adjLists);
free(graph);
return 0;
}

BMCET, SURAT 22
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

OUTPUT:

BMCET, SURAT 23
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 10
Aim: Implement prim’s algorithm.

INPUT:
#include <stdio.h>
#include <limits.h>

#define V 5 // Number of vertices in the graph

int minKey(int key[], int mstSet[]) {


int min = INT_MAX, min_index;

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


if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}

return min_index;
}

void 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]; // Array to store constructed MST
int key[V]; // Key values used to pick minimum weight edge in cut
int mstSet[V]; // To represent set of vertices included in MST

// Initialize all keys as INFINITE and mstSet[] as false


for (int i = 0; i < V; i++) {
key[i] = INT_MAX, mstSet[i] = 0;
}

// Always include first vertex in MST.


// Make key 0 so that this vertex is picked as first vertex.
key[0] = 0;
parent[0] = -1; // First node is always root of MST

BMCET, SURAT 24
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

// The MST will have V vertices


for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = minKey(key, mstSet);

// Add the picked vertex to the MST Set


mstSet[u] = 1;

// Update key value and parent index of the adjacent vertices of the picked vertex.
// Consider the adjacent vertices of the picked vertex.
// If the weight of the edge is less than the key value of the vertex,
// update the key value and parent index of the vertex.
for (int v = 0; v < V; v++) {
// graph[u][v] is non zero only for adjacent vertices of m
// mstSet[v] is false for vertices not yet included in MST
// Update the key only if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u, key[v] = graph[u][v];
}
}
}

// print the constructed MST


printMST(parent, graph);
}

int main() {
// Example graph represented as an adjacency matrix
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}
};

primMST(graph);

return 0;
}

BMCET, SURAT 25
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

OUTPUT:

BMCET, SURAT 26
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 11
Aim: Implement kruskal’s algorithm.

INPUT:
#include <stdio.h>
#include <stdlib.h>

// Comparator function to use in sorting


int comparator(const void* p1, const void* p2)
{
const int(*x)[3] = p1;
const int(*y)[3] = p2;

return (*x)[2] - (*y)[2];


}

// Initialization of parent[] and rank[] arrays


void makeSet(int parent[], int rank[], int n)
{
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}

// Function to find the parent of a node


int findParent(int parent[], int component)
{
if (parent[component] == component)
return component;

return parent[component]
= findParent(parent, parent[component]);
}

// Function to unite two sets


void unionSet(int u, int v, int parent[], int rank[], int n)
{
// Finding the parents
u = findParent(parent, u);
v = findParent(parent, v);

if (rank[u] < rank[v]) {

BMCET, SURAT 27
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

parent[u] = v;
}
else if (rank[u] > rank[v]) {
parent[v] = u;
}
else {
parent[v] = u;

// Since the rank increases if


// the ranks of two sets are same
rank[u]++;
}
}

// Function to find the MST


void kruskalAlgo(int n, int edge[n][3])
{
// First we sort the edge array in ascending order
// so that we can access minimum distances/cost
qsort(edge, n, sizeof(edge[0]), comparator);

int parent[n];
int rank[n];

// Function to initialize parent[] and rank[]


makeSet(parent, rank, n);

// To store the minimun cost


int minCost = 0;

printf(
"Following are the edges in the constructed MST\n");
for (int i = 0; i < n; i++) {
int v1 = findParent(parent, edge[i][0]);
int v2 = findParent(parent, edge[i][1]);
int wt = edge[i][2];

// If the parents are different that


// means they are in different sets so
// union them
if (v1 != v2) {
unionSet(v1, v2, parent, rank, n);
minCost += wt;
printf("%d -- %d == %d\n", edge[i][0],

BMCET, SURAT 28
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

edge[i][1], wt);
}
}

printf("Minimum Cost Spanning Tree: %d\n", minCost);


}

// Driver code
int main()
{
int edge[5][3] = { { 0, 1, 10 },
{ 0, 2, 6 },
{ 0, 3, 5 },
{ 1, 3, 15 },
{ 2, 3, 4 } };

kruskalAlgo(5, edge);

return 0;
}

OUTPUT:

BMCET, SURAT 29
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

Practical: 12
Aim: Implement the LCS problem

INPUT:
#include <stdio.h>
#include <string.h>
// Function to find the length of the LCS of two strings
int lcsLength(char *X, char *Y, int m, int n)
{
int L[m + 1][n + 1];
// Building the L table in bottom-up manner
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = (L[i - 1][j] > L[i][j - 1]) ? L[i - 1][j] : L[i][j - 1];
}
}
// Return the length of LCS
return L[m][n];
}
// Function to print the LCS of two strings
void printLCS(char *X, char *Y, int m, int n)
{
int L[m + 1][n + 1];
// Building the L table in bottom-up manner
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = (L[i - 1][j] > L[i][j - 1]) ? L[i - 1][j] : L[i][j - 1];
}
}

BMCET, SURAT 30
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028

// Reconstructing the LCS from the L table


int index = L[m][n];
char lcs[index + 1];
lcs[index] = '\0'; // Null-terminate the LCS string
int i = m, j = n;
while (i > 0 && j > 0)
{
if (X[i - 1] == Y[j - 1])
{
lcs[index - 1] = X[i - 1];
i--;
j--;
index--;
}
else if (L[i - 1][j] > L[i][j - 1])
i--;
else
j--;
}
printf("LCS: %s\n", lcs);
}
// Main function to test the above code
int main()
{
char X[] = "ABCBDAB";
char Y[] = "BDCAB";
int m = strlen(X);
int n = strlen(Y);
printf("Length of LCS: %d\n", lcsLength(X, Y, m, n));
printLCS(X, Y, m, n);
return 0;
}

OUTPUT:

BMCET, SURAT 31

You might also like