Ada Practical
Ada Practical
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];
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
BAIT,SURAT 4
Analysis & Design Of Algorithm[2010206509] 2307020703027
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
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
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);
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
BAIT,SURAT 21
Analysis & Design Of Algorithm[2010206509] 2307020703027
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
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
BAIT,SURAT 28
Analysis & Design Of Algorithm[2010206509] 2307020703027
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
************
BAIT,SURAT 31