AOA Lab Programs
Q1. Implement recursive linear and binary search and determine the time
required to search an element. Repeat the experiment for different values of n,
the number of elements in the list to be searched and the time taken versus n.
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
#include <time.h>
int a[1000], low, high, ele, pos;
// Linear Search Algorithm
int lin()
{
if (pos < 0)
{
return pos + 1;
}
else if (a[pos] == ele)
{
return pos + 1;
}
else
{
pos = pos - 1;
return lin();
}
}
// Binary Search Algorithm
int bin()
{
int mid = (low + high) / 2;
if (low > high)
{
AOA Lab Programs 1
return 0;
}
else if (a[mid] == ele)
{
return mid + 1;
}
else if (a[mid] > ele)
{
high = mid + 1;
return bin();
}
else if (a[mid] < ele)
{
low = mid + 1;
return bin();
}
}
int main()
{
int i, n, temp, choice;
int clrscr();
time_t start, end;
printf("\nEnter the number of elements: ");
scanf("%d",&n);
for(i = 0; i < n; i++)
{
printf("Enter the element: ");
scanf("%d", &a[i]);
}
printf("Enter the search element: ");
scanf("%d", &ele);
printf("Enter 1 for Binary Search and 2 for Linear Sea
rch: ");
scanf("%d", &choice);
AOA Lab Programs 2
switch (choice)
{
case 1:
start = time(NULL);
low = 0;
high = n - 1;
temp = bin();
end = time(NULL);
break;
case 2:
start = time(NULL);
pos = n - 1;
temp = lin();
end = time(NULL);
break;
default:
printf("Invalid Input!!!");
break;
}
printf("Element found at position = %d and time taken =
%.2f", temp, difftime(end, start));
}
Output:
Q2. Sort a given set of elements using selection sort method and determine the
time required to sort the elements. Repeat the experiment for different values of
AOA Lab Programs 3
n, the number of elements in the list to be sorted and the time taken versus n.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void selectionSort(int arr[], int n) {
int i, j, min_idx, temp;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first el
ement
temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int n,i;
// Input size of the array
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int* arr = (int*)malloc(n * sizeof(int));
// int arr[n]; It is not used as we are dynamically all
ocating the memory
// Input elements of the array
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++) {
AOA Lab Programs 4
scanf("%d", &arr[i]);
}
// Start measuring time
clock_t start = clock();
// Sort the array using selection sort
selectionSort(arr, n);
// Stop measuring time
clock_t end = clock();
// Calculate the time taken
double time_taken = ((double)(end - start)) / CLOCKS_PE
R_SEC;
// Output the sorted array
printf("Sorted array:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// Output the time taken
printf("Time taken to sort the array: %f seconds", time
_taken);
return 0;
}
Output:
AOA Lab Programs 5
Q3. Sort a given set of elements using quick sort method and determine the
time required to sort the elements. Repeat the experiment for different values of
n, the number of elements in the list to be sorted and the time taken versus n.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Partition function to choose a pivot and partition the a
rray
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choosing the last element as
pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++) {
// If current element is smaller than or equal to p
ivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
AOA Lab Programs 6
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
// Quick Sort function
void quickSort(int arr[], int low, int high) {
if (low < high) {
// pi is partitioning index, arr[pi] is now at righ
t place
int pi = partition(arr, low, high);
// Recursively sort elements before partition and a
fter partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int n;
// Input size of the array
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for n elements
int* arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
AOA Lab Programs 7
// Input elements of the array
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Start time measurement
clock_t start = clock();
// Perform quick sort
quickSort(arr, 0, n - 1);
// End time measurement
clock_t end = clock();
// Calculate time taken
double time_taken = ((double)(end - start)) / CLOCKS_PE
R_SEC;
// Print sorted array
printf("Sorted array: \n");
printArray(arr, n);
// Print time taken
printf("Time taken to sort the array: %f seconds", time
_taken);
// Free allocated memory
free(arr);
return 0;
}
Output:
AOA Lab Programs 8
Q4. Sort a given set of elements using merge sort method and determine the
time required to sort the elements. Repeat the experiment for different values of
n, the number of elements in the list to be sorted and the time taken versus n.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to merge two subarrays
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
// Create temporary arrays
int* L = (int*)malloc(n1 * sizeof(int));
int* R = (int*)malloc(n2 * sizeof(int));
// Copy data to temporary arrays L[] and R[]
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
// Merge the temporary arrays back into arr[left..righ
t]
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = left; // Initial index of merged subarray
while (i < n1 && j < n2) {
AOA Lab Programs 9
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of R[], if there are any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
// Free the temporary arrays
free(L);
free(R);
}
// Function to implement merge sort
void mergeSort(int arr[], int left, int right) {
if (left < right) {
// Find the middle point
int mid = left + (right - left) / 2;
// Recursively sort first and second halves
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
AOA Lab Programs 10
// Merge the sorted halves
merge(arr, left, mid, right);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int n;
// Input size of the array
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for n elements
int* arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input elements of the array
printf("Enter the elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Start time measurement
clock_t start = clock();
// Perform merge sort
mergeSort(arr, 0, n - 1);
AOA Lab Programs 11
// End time measurement
clock_t end = clock();
// Calculate time taken
double time_taken = ((double)(end - start)) / CLOCKS_PE
R_SEC;
// Print sorted array
printf("Sorted array: \n");
printArray(arr, n);
// Print time taken
printf("Time taken to sort the array: %f seconds\n", ti
me_taken);
// Free allocated memory
free(arr);
return 0;
}
Output:
Q5. Sort a given set of elements using heap sort method and determine the
time required to sort the elements. Repeat the experiment for different values of
n, the number of elements in the list to be sorted and the time taken versus n.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Function to swap two elements
AOA Lab Programs 12
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to heapify a subtree rooted with node i which i
s an index in arr[]
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (left < n && arr[left] > arr[largest])
largest = left;
// If right child is larger than largest so far
if (right < n && arr[right] > arr[largest])
largest = right;
// If largest is not root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
// Main function to implement heap sort
void heapSort(int arr[], int n) {
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
AOA Lab Programs 13
swap(&arr[0], &arr[i]);
// Call heapify on the reduced heap
heapify(arr, i, 0);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int n;
// Input size of the array
printf("Enter the number of elements: ");
scanf("%d", &n);
// Dynamically allocate memory for n elements
int* arr = (int*)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
// Input elements of the array
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Start time measurement
clock_t start = clock();
// Perform heap sort
heapSort(arr, n);
AOA Lab Programs 14
// End time measurement
clock_t end = clock();
// Calculate time taken
double time_taken = ((double)(end - start)) / CLOCKS_PE
R_SEC;
// Print sorted array
printf("Sorted array: \n");
printArray(arr, n);
// Print time taken
printf("Time taken to sort the array: %f seconds", time
_taken);
// Free allocated memory
free(arr);
return 0;
}
Output:
Q6. Find the minimum cost spanning tree of a given undirected graph using
Kruskal's algorithm.
#include <stdio.h>
#include <stdlib.h>
// Structure to represent an edge
typedef struct {
AOA Lab Programs 15
int src, dest, weight;
} Edge;
// Structure to represent a subset for union-find
typedef struct {
int parent;
int rank;
} Subset;
// Function to compare two edges (used for sorting)
int compareEdges(const void* a, const void* b) {
return ((Edge*)a)->weight - ((Edge*)b)->weight;
}
// Find function with path compression
int find(Subset subsets[], int i) {
if (subsets[i].parent != i) {
subsets[i].parent = find(subsets, subsets[i].paren
t);
}
return subsets[i].parent;
}
// Union function by rank
void unionSets(Subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
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++;
}
}
AOA Lab Programs 16
// Function to implement Kruskal's algorithm
int kruskalMST(Edge edges[], int V, int E) {
int totalCost = 0; // Variable to store the total cost
of the MST
int e = 0; // Index used for result[]
int i = 0; // Index used for sorted edges
// Step 1: Sort all the edges in non-decreasing order o
f their weight
qsort(edges, E, sizeof(edges[0]), compareEdges);
// Allocate memory for creating V subsets
Subset *subsets = (Subset*)malloc(V * sizeof(Subset));
for (int v = 0; v < V; v++) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
// Step 2: Pick the smallest edge and increment the ind
ex for the next iteration
while (e < V - 1 && i < E) {
// Step 2a: Pick the smallest edge
Edge next_edge = edges[i++];
// Find the subsets of the vertices
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) {
totalCost += next_edge.weight; // Add the weigh
t to the total cost
unionSets(subsets, x, y);
e++; // Increment the count of edges in the MST
}
}
// Free allocated memory
AOA Lab Programs 17
free(subsets);
return totalCost; // Return the total cost of the MST
}
int main() {
int V, E;
// Input number of vertices and edges
printf("Enter the number of vertices: ");
scanf("%d", &V);
printf("Enter the number of edges: ");
scanf("%d", &E);
Edge* edges = (Edge*)malloc(E * sizeof(Edge));
// Input edges
printf("Enter the edges (src dest weight):\n");
for (int i = 0; i < E; i++) {
scanf("%d %d %d", &edges[i].src, &edges[i].dest, &e
dges[i].weight);
}
// Function call to find the MST using Kruskal's algori
thm
int minCost = kruskalMST(edges, V, E);
// Print the total cost of the MST
printf("Minimum cost of the MST: %d", minCost);
// Free allocated memory
free(edges);
return 0;
}
Output:
AOA Lab Programs 18
Q7. Find the minimum cost spanning tree of a given undirected graph using
Prim's algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100 // Maximum number of vertices
// Function to find the vertex with the minimum key value
int minKey(int key[], int mstSet[], int V) {
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;
}
// Function to implement Prim's algorithm
int primMST(int graph[MAX_VERTICES][MAX_VERTICES], int V) {
int parent[MAX_VERTICES]; // Array to store constructed
MST
int key[MAX_VERTICES]; // Key values used to pick mi
nimum weight edge
int mstSet[MAX_VERTICES]; // To represent the set of ve
AOA Lab Programs 19
rtices included in the MST
// Initialize all keys as INFINITE and mstSet[] as fals
e
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0;
}
// Always include the first vertex in the MST
key[0] = 0; // Make key 0 so that this vertex is pic
ked as the first
parent[0] = -1; // First node is always the root of the
MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vert
ices not yet included in the MST
int u = minKey(key, mstSet, V);
// Add the picked vertex to the MST Set
mstSet[u] = 1;
// Update the key value and parent index of the adj
acent vertices of the picked vertex
for (int v = 0; v < V; v++) {
// Update the key only if graph[u][v] is smalle
r than key[v]
if (graph[u][v] && mstSet[v] == 0 && graph[u]
[v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Calculate the total cost of the MST
AOA Lab Programs 20
int totalCost = 0;
for (int i = 1; i < V; i++) {
totalCost += graph[i][parent[i]];
}
return totalCost; // Return the total cost of the MST
}
int main() {
int V;
int graph[MAX_VERTICES][MAX_VERTICES];
// Input the number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &V);
// Input the adjacency matrix for the graph
printf("Enter the adjacency matrix (use 0 for no edg
e):\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}
// Function call to find the MST using Prim's algorithm
int minCost = primMST(graph, V);
// Print the total cost of the MST
printf("Minimum cost of the Minimum Spanning Tree: %d",
minCost);
return 0;
}
Output:
AOA Lab Programs 21
Q8. Implement 0/1 knapsack using dynamic programming.
#include <stdio.h>
#define MAX_ITEMS 100
#define MAX_CAPACITY 1000
// Function to find the maximum value that can be put in a
knapsack of capacity W
int knapsack(int capacity, int weights[], int values[], int
n) {
int i, w;
int K[MAX_ITEMS + 1][MAX_CAPACITY + 1];
// Build table K[][] in bottom-up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= capacity; w++) {
if (i == 0 || w == 0) {
K[i][w] = 0; // Base case: no items or no c
apacity
} else if (weights[i - 1] <= w) {
K[i][w] = (values[i - 1] + K[i - 1][w - wei
ghts[i - 1]] > K[i - 1][w]) ?
values[i - 1] + K[i - 1][w - we
ights[i - 1]] : K[i - 1][w];
} else {
K[i][w] = K[i - 1][w]; // Item cannot be in
cluded
}
}
AOA Lab Programs 22
}
return K[n][capacity]; // Maximum value that can be put
in the knapsack
}
int main() {
int n, capacity;
int weights[MAX_ITEMS], values[MAX_ITEMS];
// Input number of items and capacity of the knapsack
printf("Enter number of items: ");
scanf("%d", &n);
printf("Enter capacity of the knapsack: ");
scanf("%d", &capacity);
// Input weights and values of items
printf("Enter weights of items:\n");
for (int i = 0; i < n; i++) {
printf("Weight of item %d: ", i + 1);
scanf("%d", &weights[i]);
}
printf("Enter values of items:\n");
for (int i = 0; i < n; i++) {
printf("Value of item %d: ", i + 1);
scanf("%d", &values[i]);
}
// Function call to find the maximum value
int maxValue = knapsack(capacity, weights, values, n);
// Print the maximum value that can be put in the knaps
ack
printf("Maximum value in the knapsack: %d\n", maxValu
e);
AOA Lab Programs 23
return 0;
}
Output:
Q9. From a given vertex in a weighted connected graph, find shortest paths to
other vertices using Dijkstra's algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_VERTICES 100
// Function to find the vertex with the minimum distance va
lue
int minDistance(int dist[], int sptSet[], int V) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (sptSet[v] == 0 && dist[v] < min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
AOA Lab Programs 24
// Function to implement Dijkstra's algorithm
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int sr
c, int V) {
int dist[MAX_VERTICES]; // Output array. dist[i] holds
the shortest distance from src to i
int sptSet[MAX_VERTICES]; // sptSet[i] will be true if
vertex i is included in the shortest path tree
// Initialize all distances as INFINITE and sptSet[] as
false
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
}
// Distance from source to itself is always 0
dist[src] = 0;
// Find the shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of
vertices not yet processed
int u = minDistance(dist, sptSet, V);
// Mark the picked vertex as processed
sptSet[u] = 1;
// Update dist value of the adjacent vertices of th
e picked vertex
for (int v = 0; v < V; v++) {
// Update dist[v] if and only if it is not in s
ptSet, there is an edge from u to v,
// and the total weight of the path from src to
v through u is smaller than the current value of dist[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];
AOA Lab Programs 25
}
}
}
// Print the constructed distance array
printf("Vertex\tDistance from Source\n");
for (int i = 0; i < V; i++) {
printf("%d\t%d\n", i, dist[i]);
}
}
int main() {
int V;
int graph[MAX_VERTICES][MAX_VERTICES];
// Input the number of vertices
printf("Enter the number of vertices: ");
scanf("%d", &V);
// Input the adjacency matrix for the graph
printf("Enter the adjacency matrix (use 0 for no edg
e):\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
scanf("%d", &graph[i][j]);
}
}
int source;
printf("Enter the source vertex (0 to %d): ", V - 1);
scanf("%d", &source);
// Function call to find the shortest paths using Dijks
tra's algorithm
dijkstra(graph, source, V);
return 0;
}
AOA Lab Programs 26
Output:
Q10. Implement N Queens problem using back tracking.
#include <stdio.h>
#include <stdbool.h>
#define MAX_N 20 // Maximum size of the chessboard
int board[MAX_N][MAX_N]; // Chessboard representation
// Function to print the chessboard
void printBoard(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 1)
printf(" Q ");
else
printf(" . ");
}
printf("\n");
}
printf("\n");
}
// Function to check if a queen can be placed at board[row]
[col]
AOA Lab Programs 27
bool isSafe(int board[MAX_N][MAX_N], int row, int col, int
n) {
// Check the column
for (int i = 0; i < row; i++) {
if (board[i][col] == 1)
return false;
}
// Check the upper left diagonal
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (board[i][j] == 1)
return false;
}
// Check the upper right diagonal
for (int i = row, j = col; i >= 0 && j < n; i--, j++) {
if (board[i][j] == 1)
return false;
}
return true;
}
// Backtracking function to solve N Queens problem
bool solveNQueens(int board[MAX_N][MAX_N], int row, int n)
{
if (row >= n) {
return true; // All queens are placed
}
for (int col = 0; col < n; col++) {
if (isSafe(board, row, col, n)) {
// Place the queen
board[row][col] = 1;
// Recur to place the rest of the queens
if (solveNQueens(board, row + 1, n)) {
AOA Lab Programs 28
return true;
}
// If placing queen in the current position doe
sn't lead to a solution,
// remove the queen (backtrack)
board[row][col] = 0;
}
}
return false; // No place is safe for the queen
}
int main() {
int n;
printf("Enter the number of queens (N): ");
scanf("%d", &n);
// Initialize the chessboard
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = 0; // 0 means no queen is placed
}
}
if (solveNQueens(board, 0, n)) {
printf("One of the possible solutions is:\n");
printBoard(n);
} else {
printf("No solution exists for %d queens.\n", n);
}
return 0;
}
Output:
AOA Lab Programs 29
AOA Lab Programs 30