AOA Lab Manual
AOA Lab Manual
For
Analysis of Algorithm
Semester IV
Computer Engineering
(2024-25)
List of Experiment
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting
the smallest (or largest) element from the unsorted portion of the list and moving it to the
sorted portion of the list.
The algorithm repeatedly selects the smallest (or largest) element from the unsorted portion
of the list and swaps it with the first element of the unsorted part. This process is repeated
for the remaining unsorted portion until the entire list is sorted.
Selection Sort Algorithm in C
selectionSort(array, size)
loop i from 0 to size - 2
set minIndex as i
loop j from first unsorted to size - 1
check if array[j] < array[minIndex]
set minIndex as j
swap array[i] with array[minIndex]
end for
end selectionSort
Output
Unsorted array:
64 25 12 22 11
Sorted array:
11 12 22 25 64
Insertion Sort
Insertion sort is a simple sorting algorithm that works similarly to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an unsorted part.
Values from the unsorted part are picked and placed in the correct position in the sorted
part.
Algorithm
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
return 0;
}
Output
Unsorted array: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Conclusion: Thus we have studied about Selection sort and Insertion sort.
Experiment No 2
Algorithm:
Step 1: Start
Step 2: Declare an array and left, right, mid variable
Step 3: Perform merge function.
mergesort(array,left,right)
mergesort (array, left, right)
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
Step 4: Stop
Program
// C program for Merge Sort //
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int leftArr[n1], rightArr[n2];
for (i = 0; i < n1; i++)
leftArr[i] = arr[left + i];
for (j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
}
else {
arr[k] = rightArr[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = leftArr[i];
i++;
k++;
}
int main() {
int arr[] = { 12, 11, 13, 5, 6, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
Output
5 6 7 11 12 13
Binary Search
A quick method for locating a particular element in a sorted array is a binary search. The initial
task of this algorithm is to compare the target value to the array's middle element. The search
is deemed successful if the target value is contained in the middle element. The algorithm will
look in the left half of the array if the goal value is less than the centre element. The programme
will scan the right half of the array if the goal value is greater than the centre element. This
method is repeated until either the goal value or the search range is exhausted.
Step 1 − Select the middle item in the array and compare it with the key value to be searched.
If it is matched, return the position of the median.
Step 2 − If it does not match the key value, check if the key value is either greater than or less
than the median value.
Step 3 − If the key is greater, perform the search in the right sub-array; but if the key is lower
than the median value, perform the search in the left sub-array.
Step 4 − Repeat Steps 1, 2 and 3 iteratively, until the size of sub-array becomes 1.
Step 5 − If the key value does not exist in the array, then the algorithm returns an
unsuccessful search.
Program
#include <stdio.h>
int binarySearch(int array[], int x, int low, int high) {
// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;
if (x == array[mid])
return mid;
if (x > array[mid])
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}
Output
Element is found at index 1
Conclusion: Thus we have studied about Merge sort and Binary search.
Experiment No 3
Aim: Write a program to find Single source shortest path- Dijkstra using greedy method
approach.
The algorithm maintains a set of visited vertices and a set of unvisited vertices. It starts at
the source vertex and iteratively selects the unvisited vertex with the smallest tentative
distance from the source. It then visits the neighbours of this vertex and updates their
tentative distances if a shorter path is found. This process continues until the destination
vertex is reached, or all reachable vertices have been visited.
Algorithm for Dijkstra’s Algorithm:
v.d := ∞
v.∏ := NIL
s.d := 0
S := Ф
Q := G.V
while Q ≠ Ф
u := Extract-Min (Q)
S := S U {u}
v.∏ := u
Program
distance[start] = 0;
visited_nodes[start] = 1;
counter = 1;
visited_nodes[next_node] = 1;
for (i = 0; i < size; i++)
if (!visited_nodes[i])
if (minimum_distance + cost[next_node][i] < distance[i]) {
distance[i] = minimum_distance + cost[next_node][i];
previous[i] = next_node;
}
counter++;
}
// main function
int main() {
// defining variables
int Graph[MAX][MAX], i, j, size, source;
// declaring the size of the matrix
size = 7;
Graph[2][0] = 0;
Graph[2][1] = 8;
Graph[2][2] = 0;
Graph[2][3] = 7;
Graph[2][4] = 0;
Graph[2][5] = 4;
Graph[2][6] = 0;
Graph[3][0] = 0;
Graph[3][1] = 0;
Graph[3][2] = 7;
Graph[3][3] = 0;
Graph[3][4] = 9;
Graph[3][5] = 14;
Graph[3][6] = 0;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 0;
Graph[4][3] = 9;
Graph[4][4] = 0;
Graph[4][5] = 10;
Graph[4][6] = 2;
Graph[5][0] = 0;
Graph[5][1] = 0;
Graph[5][2] = 4;
Graph[5][3] = 14;
Graph[5][4] = 10;
Graph[5][5] = 0;
Graph[5][6] = 2;
Graph[6][0] = 0;
Graph[6][1] = 0;
Graph[6][2] = 0;
Graph[6][3] = 0;
Graph[6][4] = 2;
Graph[6][5] = 0;
Graph[6][6] = 1;
source = 0;
// calling the DijkstraAlgorithm() function by passing the Graph, the number of nodes and
the source node
DijkstraAlgorithm(Graph, size, source);
return 0;
}
Output
Theory:
Algorithm
#include <stdio.h>
void floyds(int b[3][3]) { int i, j, k;
for (k = 0; k < 3; k++) { for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if ((b[i][k] * b[k][j] != 0) && (i != j)) {
if ((b[i][k] + b[k][j] < b[i][j]) || (b[i][j] == 0)) { b[i][j] = b[i][k] + b[k][j];
}
}
}
}
}
for (i = 0; i < 3; i++) {
printf("Minimum Cost With Respect to Node: %d\n", i); for (j = 0; j < 3; j++) {
printf("%d\t", b[i][j]);
}
}
}
int main() {
int b[3][3] = {0};
b[0][1] = 10;
b[1][2] = 15;
b[2][0] = 12;
floyds(b); return 0;
}
Output
Theory:
Definition
Given a set of cities and the distance between each possible pair, the Travelling
Salesman Problem is to find the best possible way of ‘visiting all the cities exactly
once and returning to the starting point’.
The (original) problem can be formulated as:"If there are n cities a salesman must
visit, and the distance between each pair of these cities is given, find the shortest
tour where each city is visited exactly once and returning to your starting point."
Dynamic Programming
Dynamic programming is typically applied to optimization problems. For each
given problem, we may get any number of solutions we seek for optimum solution
(i.e. minimum value or maximum value solution). And such an optimal solution
becomes the solution to the given problem. It is guaranteed that the dynamic
programming will generate optimal solution using principle of optimality.
A tour for a graph should be such that all the vertices should be visited only once
andcost of the tour is sum of the cost of edges on the tour. The travelling
salesperson problem is to find the tour of minimum cost.
#include <stdio.h>
#include <limits.h>
#define MAX 9999
int n = 4;
int distan[20][20] = {
{0, 22, 26, 30},
{30, 0, 45, 35},
{25, 45, 0, 60},
{30, 35, 40, 0}};
int DP[32][8];
int TSP(int mark, int position) {
int completed_visit = (1 << n) - 1;
if (mark == completed_visit) {
return distan[position][0];
}
if (DP[mark][position] != -1) {
return DP[mark][position];
}
int answer = MAX;
for (int city = 0; city < n; city++) {
if ((mark & (1 << city)) == 0) {
int newAnswer = distan[position][city] + TSP(mark | (1 << city), city);
answer = (answer < newAnswer) ? answer : newAnswer;
}
}
return DP[mark][position] = answer;
}
int main() {
for (int i = 0; i < (1 << n); i++) {
for (int j = 0; j < n; j++) {
DP[i][j] = -1;
}
}
printf("Minimum Distance Travelled -> %d\n", TSP(1, 0));
return 0;
}
Output
Minimum Distance Travelled -> 122
Conclusion: Thus we have studied about travelling salesperson problem using Dynamic
programming.
Experiment No 6
Aim: Write a program to find longest common subsequence using Dynamic programming.
Theory:
The longest common subsequence problem is finding the longest sequence which exists in
both the given strings.
But before we understand the problem, let us understand what the term subsequence is −
Let us consider a sequence S = <s1, s2, s3, s4, …,sn>. And another sequence Z = <z1, z2, z3,
…,zm> over S is called a subsequence of S, if and only if it can be derived from S deletion of
some elements. In simple words, a subsequence consists of consecutive elements that make
up a small part in a sequence.
Common Subsequence
Suppose, X and Y are two sequences over a finite set of elements. We can say that Z is a
common subsequence of X and Y, if Z is a subsequence of both X and Y.
If a set of sequences are given, the longest common subsequence problem is to find a
common subsequence of all the sequences that is of maximal length.
Output: 4
Output: 2
#include <stdio.h>
#include <string.h>
int main()
{
// First string
char X[] = "AGGTAB";
// Second string
char Y[] = "GXTXAYB";
// Length of first string
int m = strlen(X);
// Length of second string
int n = strlen(Y);
return 0;
}
Output
Length of LCS is 4
Aim: Write a program to find N-queen problem using Backtracking and Branch and bound.
Theory:
Let’s begin by describing the backtracking solution. “The idea is to place queens one by
one in different columns, starting from the leftmost column. When we place a queen in a
column, we check for clashes with already placed queens. In the current column, if we find
a row for which there is no clash, we mark this row and column as part of the solution. If
we do not find such a row due to clashes, then we backtrack and return false.”
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int N;
int main()
{
// Taking input from the user for the size of the board
printf(
"Enter the number of rows for the square board: ");
scanf("%d", &N);
return 0;
}
Input:
Enter the no of rows for the square Board: 8
Output:
1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 1
0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 0 0
Theory:
#include <stdio.h>
#include <string.h>
int main() {
// Example 1
char txt1[] = "AABAACAADAABAABA";
char pat1[] = "AABA";
printf("Example 1:\n");
search(pat1, txt1);
// Example 2
char txt2[] = "agd";
char pat2[] = "g";
printf("\nExample 2:\n");
search(pat2, txt2);
return 0;
}
Output:
Theory:
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char
txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// lps[0] is always 0
lps[0] = 0;
if (j == M) {
}
printf("\n");
return 0;
}
Output:
Theory:
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char
txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m.
Examples:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm,
Rabin Karp algorithm matches the hash value of the pattern with the hash value of current
substring of text, and if the hash values match then only it starts matching individual
characters. So Rabin Karp algorithm needs to calculate hash values for following strings.
1) Pattern itself.
2) All the substrings of text of length m.
Program
/* Driver Code */
int main()
{
char txt[] = "GEEKS FOR GEEKS";
char pat[] = "GEEK";
// A prime number
int q = 101;
// function call
search(pat, txt, q);
return 0;
}
Output:
Pattern found at index 0
Pattern found at index 10