Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Ada Practical

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 Practical

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 Algorithm[2010206509] 2307020703027

PRACTICAL-1
AIM:-Implementation and Time analysis of sorting algorithms. Bubblesort,
Selection sort, Insertion sort, Merge sort and Quicksort.

INPUT:

#include <stdio.h>
// Function to print an array
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;
}
}
int temp = arr[min_idx];

BAIT,SURAT 1
Analysis & Design Of Algorithm[2010206509] 2307020703027

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 Function
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++;
}
k++;

BAIT,SURAT 2
Analysis & Design Of Algorithm[2010206509] 2307020703027

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

BAIT,SURAT 3
Analysis & Design Of Algorithm[2010206509] 2307020703027

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);
// Uncomment the sorting algorithm you want to use
// bubbleSort(arr, n);
// selectionSort(arr, n);
// insertionSort(arr, n);
// mergeSort(arr, 0, n - 1);
// quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
OUTPUT:

BAIT,SURAT 4
Analysis & Design Of Algorithm[2010206509] 2307020703027

Summary of Time Complexities:

Sorting Algorithm Best Case Worst Case Average Case

Bubble Sort O(n) O(n²) O(n²)

Selection Sort O(n²) O(n²) O(n²)

Insertion Sort O(n) O(n²) O(n²)

Merge Sort O(n log n) O(n log n) O(n log n)

Quicksort O(n log n) O(n²) O(n log n)

BAIT,SURAT 5
Analysis & Design Of Algorithm[2010206509] 2307020703027

● Bubble Sort, Selection Sort, and Insertion Sort are simple but inefficient for large datasets
with a time complexity of O(n²).
● Merge Sort and Quicksort are more efficient with time complexities of O(n log n), but
Quicksort can degrade to O(n²) if the pivot is poorly chosen.

BAIT,SURAT 6
Analysis & Design Of Algorithm[2010206509] 2307020703027

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[] = {10, 20, 30, 40, 50, 60, 70};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 40;

// Linear search

BAIT,SURAT 7
Analysis & Design Of Algorithm[2010206509] 2307020703027

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:

Searching Algorithm Best Case Worst Case Average Case

Linear Search O(1) O(n) O(n)

Binary Search O(1) O(log n) O(log n)

BAIT,SURAT 8
Analysis & Design Of Algorithm[2010206509] 2307020703027

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--) {
heapify(arr, n, i);

BAIT,SURAT 9
Analysis & Design Of Algorithm[2010206509] 2307020703027

}
// 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[] = {12, 11, 13, 5, 6, 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:

BAIT,SURAT 10
Analysis & Design Of Algorithm[2010206509] 2307020703027

PRACTICAL-4
AIM: Implementation and Time analysis of factorial program using iterative and
recursive method.
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; // Example: Factorial of 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:

BAIT,SURAT 11
Analysis & Design Of Algorithm[2010206509] 2307020703027

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

BAIT,SURAT 12
Analysis & Design Of Algorithm[2010206509] 2307020703027

OUTPUT:

BAIT,SURAT 13
Analysis & Design Of Algorithm[2010206509] 2307020703027

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() {
// Example dimensions of matrices:
// A1 (30x35), A2 (35x15), A3 (15x5), A4 (5x10), A5 (10x20), A6 (20x25)
int arr[] = {30, 35, 15, 5, 10, 20, 25};

BAIT,SURAT 14
Analysis & Design Of Algorithm[2010206509] 2307020703027

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


// Call the matrixChainOrder function
int minMultiplications = matrixChainOrder(arr, size);
// Print the result
printf("Minimum number of multiplications is: %d\n", minMultiplications);
return 0;
}

OUTPUT:

BAIT,SURAT 15
Analysis & Design Of Algorithm[2010206509] 2307020703027

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
int result = minCoins(coins, n, amount);
if (result == -1) {

BAIT,SURAT 16
Analysis & Design Of Algorithm[2010206509] 2307020703027

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:

BAIT,SURAT 17
Analysis & Design Of Algorithm[2010206509] 2307020703027

PRACTICAL-8
AIM: Implementation of a knapsack problem using greedy algorithm.

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++) {
// If the item can fit in the knapsack, take it completely

BAIT,SURAT 18
Analysis & Design Of Algorithm[2010206509] 2307020703027

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[] = { {60, 10}, {100, 20}, {120, 30} }; // 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:

BAIT,SURAT 19
Analysis & Design Of Algorithm[2010206509] 2307020703027

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

BAIT,SURAT 20
Analysis & Design Of Algorithm[2010206509] 2307020703027

// Add an edge from src to dest


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

BAIT,SURAT 21
Analysis & Design Of Algorithm[2010206509] 2307020703027

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

BAIT,SURAT 22
Analysis & Design Of Algorithm[2010206509] 2307020703027

}
}
// 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, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
// 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;
}

BAIT,SURAT 23
Analysis & Design Of Algorithm[2010206509] 2307020703027

OUTPUT:

BAIT,SURAT 24
Analysis & Design Of Algorithm[2010206509] 2307020703027

PRACTICAL-10
AIM: Implement prim’s algorithm.

INPUT:
#include <stdio.h>
#include <limits.h> // For INT_MAX
#define V 5 // Number of vertices in the graph
// Function to find the vertex with the minimum key value
int minKey(int key[], bool mstSet[]) {
int min = INT_MAX, minIndex;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
// Function to print the constructed MST
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]]);
}
}
// Function to implement Prim's Algorithm
void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values to pick the minimum weight edge
bool mstSet[V]; // To check if a vertex is 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] = false;
}
// Always include the first vertex in the MST
key[0] = 0;

BAIT,SURAT 25
Analysis & Design Of Algorithm[2010206509] 2307020703027

parent[0] = -1; // First node is the root of MST


// 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 processed
int u = minKey(key, mstSet);
// Add the picked vertex to the MST set
mstSet[u] = true;
// Update key value and parent index of the adjacent vertices of the picked vertex
for (int v = 0; v < V; v++) {
// Update key[v] if and only if graph[u][v] is smaller than key[v]
if (graph[u][v] && !mstSet[v] && 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;
}
OUTPUT:

BAIT,SURAT 26
Analysis & Design Of Algorithm[2010206509] 2307020703027

PRACTICAL-11
AIM: Implement kruskal’s algorithm.

INPUT:
#include <stdio.h>
#include <stdlib.h>
// Structure to represent a graph edge
typedef struct {
int src, dest, weight;
} Edge;
// Structure to represent a subset for union-find
typedef struct {
int parent, rank;
} Subset;
// Function to find the set of an element i
int find(Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent); // Path compression
return subsets[i].parent;
}
// Function to do union of two sets of x and y
void unionSets(Subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (xroot != yroot) {
// Union by rank
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
}
// Comparison function for sorting edges by weight

BAIT,SURAT 27
Analysis & Design Of Algorithm[2010206509] 2307020703027

int compareEdges(const void *a, const void *b) {


return ((Edge *)a)->weight - ((Edge *)b)->weight;
}
// Function to implement Kruskal's algorithm
void kruskal(Edge edges[], int V, int E) {
Edge result[V]; // Array to store the resultant MST
int e = 0; // Index for result[]
int i = 0; // Index for sorted edges
// Step 1: Sort all the edges in non-decreasing order of their weight
qsort(edges, E, sizeof(Edge), compareEdges);
// Allocate memory for creating V subsets
Subset *subsets = (Subset *)malloc(V * sizeof(Subset));
// Create V subsets with single elements
for (int v = 0; v < V; ++v) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
// Number of edges to be taken is equal to V-1
while (e < V - 1 && i < E) {
// Step 2: Pick the smallest edge
Edge next_edge = edges[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
// If including this edge does not cause a cycle
if (x != y) {
result[e++] = next_edge;
unionSets(subsets, x, y);
}
}
// Print the result
printf("Edges in the Minimum Spanning Tree:\n");
for (i = 0; i < e; ++i) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight);
}
// Free allocated memory
free(subsets);
}

BAIT,SURAT 28
Analysis & Design Of Algorithm[2010206509] 2307020703027

// Main function to test the above code


int main() {
// Number of vertices and edges in the graph
int V = 4;
int E = 5;
// Array of edges (source, destination, weight)
Edge edges[] = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4}
};
// Function call
kruskal(edges, V, E);
return 0;
}

OUTPUT:

BAIT,SURAT 29
Analysis & Design Of Algorithm[2010206509] 2307020703027

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

BAIT,SURAT 30
Analysis & Design Of Algorithm[2010206509] 2307020703027

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

************

BAIT,SURAT 31

You might also like