ADA LabManual Aayush
ADA LabManual Aayush
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
// 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);
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
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
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
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
BMCET, SURAT 20
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028
BMCET, SURAT 21
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028
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>
return min_index;
}
BMCET, SURAT 24
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028
// 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];
}
}
}
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>
return parent[component]
= findParent(parent, parent[component]);
}
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;
int parent[n];
int rank[n];
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];
BMCET, SURAT 28
Analysis & Design of Algorithms- Practical (2010206509) 2328020603028
edge[i][1], wt);
}
}
// 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
OUTPUT:
BMCET, SURAT 31