You are on page 1of 31

KANPUR INSTITUTE OF

TECHNOLOGY

Design And Analysis Of


Algorithm Lab (KCS-553)
Submitted by:
Krishna Singh
Roll No-2101650130004

B.TECH.CS/CS –IT 3rd year

Session 2023-24

Submitted to:
Mr. Narendra Kumar Rajput
(Assistant Professor)

Department of Computer Science & Engineering


Vision and Mission of the Department
Vision
Computer Science Department at Kanpur Institute of Technology is
committed to empower its students with relevant and current technology so
that they are prepared to compute in this globalized technical world along
with being aware of their ethical responsibilities towards the world at large.

Mission
M1: To impart high quality education in the science of computing.
M2: To prepare educated and skilled computer professionals.
M3: To create excellence by providing comprehensive knowledge of the
latest tools and technologies in the domain of computer science, so that
students strive to become leaders.
M4: To inculcate ethical values in students so that they understand their
responsibility towards the nation with focus on upliftment of all sections of
society.
M5: To facilitate establishment of research centers and encourage students
to solve complex technological problems.
Program Educational Objectives
PEO1: Make valuable contributions to design, development and
production in the practice of computer science and engineering in related
engineering areas or application areas, and at the interface of computers
and physical systems.

PEO2: Promotes design, research and implementation of products through


strong communication skills, leadership and entrepreneurial skills.

PEO3: Engage in professional development or post-graduate education to


pursue flexible career paths amid future technological changes.

PEO4: Apply basic principles and practices of computing and science to


successfully complete software related projects to meet customer business
objectives and/or productively engage in research.

PEO5: To develop analytical, mathematical and scientific knowledge that


is used to analyze, formulate and solve any engineering problems.

Program specific outcomes (PSO’s):


PSO1: Ability to understand the mathematical methodology to cracks
problems using suitable data structure and mathematical approach.

PSO2: Ability to design and develop software for web based and mobiles
androids under real world environment.

PSO3: Ability to design the algorithm for machine learning, data


compression and IOT based application and also the successful career and
entrepreneurship.
INDEX

S. No Name of Experiment Page Date Signature


No.
1. Program for Recursive Binary & Linear Search 05-06 08/09/2023

2. Program for Heap Sort. 07-08 15/09/2023

3. Program for Merge Sort. 09-11 22/09/2023

4. Program for Selection Sort. 12-13 29/09/2023

5. Program for Insertion Sort. 14-15 13/10/2023

6. Program for Quick Sort. 16-17 20/10/2023

7. Find Minimum Spanning Tree using Kruskal’s 18-21 03/11/2023


Algorithm.
8. Find Minimum Cost Spanning Tree of a given 22-26 24/11/2023
undirected graph using Prim’s algorithm.
9 Implement N Queen Problem using Backtracking. 27-27 01/12/2023

10 From a given vertex in a weighted connected graph, 28-30 08/12/2023


find shortest paths to other vertices using Dijkstra's
algorithm.
Exp 01 : Program for Recursive Binary & Linear Search

Program: Here's a simple implementation of recursive binary search and


linear search in C:

#include <stdio.h>

// Recursive Binary Search


int binarySearchRecursive(int arr[], int low, int high, int target) {
if (low <= high) {
int mid = (low + high) / 2;

if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
return binarySearchRecursive(arr, mid + 1, high, target);
} else {
return binarySearchRecursive(arr, low, mid - 1, target);
}
} else {
return -1; // Target not found
}
}

// Linear Search
int linearSearch(int arr[], int size, int target) {
for (int i = 0; i < size; ++i) {
if (arr[i] == target) {
return i; // Target found
}
}
return -1; // Target not found
}

int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int size = sizeof(arr) / sizeof(arr[0]);
int targetBinary = 7;
int targetLinear = 3;

// Binary Search
int resultBinary = binarySearchRecursive(arr, 0, size - 1, targetBinary);
if (resultBinary != -1) {
printf("Binary Search: Element %d found at index %d\n", targetBinary,
resultBinary);
} else {
printf("Binary Search: Element %d not found\n", targetBinary);
}

// Linear Search
int resultLinear = linearSearch(arr, size, targetLinear);
if (resultLinear != -1) {
printf("Linear Search: Element %d found at index %d\n", targetLinear,
resultLinear);
} else {
printf("Linear Search: Element %d not found\n", targetLinear);
}

return 0;
}

Output:

Binary Search: Element 7 found at index 6


Linear Search: Element 3 found at index 2
Exp 02 : Program for Heap Sort

Program: Here's a simple implementation of Heap Sort in C with output:


#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int arr[], int size, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < size && arr[left] > arr[largest]) {


largest = left;
}

if (right < size && arr[right] > arr[largest]) {


largest = right;
}

if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, size, largest);
}
}

void heapSort(int arr[], int size) {


// Build max heap
for (int i = size / 2 - 1; i >= 0; i--) {
heapify(arr, size, i);
}

// Extract elements from the heap


for (int i = size - 1; i > 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

heapSort(arr, size);

printf("Sorted array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 12 11 13 5 6 7
Sorted array: 5 6 7 11 12 13
Exp 03 : Program for Merge Sort

Program: Here's a simple implementation of Merge Sort in C with output:


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

// Create temporary arrays


int L[n1], R[n2];

// 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..right]


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) {
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++;
}
}

void mergeSort(int arr[], int left, int right) {


if (left < right) {
// Same as (left + right) / 2, but avoids overflow for large left and right
int mid = left + (right - left) / 2;

// Sort first and second halves


mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);

// Merge the sorted halves


merge(arr, left, mid, right);
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

mergeSort(arr, 0, size - 1);

printf("Sorted array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 12 11 13 5 6 7
Sorted array: 5 6 7 11 12 13
Exp 04 : Program for Selection Sort

Program: Here's a simple implementation of Selection Sort in C with output:


#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void selectionSort(int arr[], int size) {


int i, j, minIndex;

// One by one move boundary of the unsorted subarray


for (i = 0; i < size - 1; i++) {
// Find the minimum element in unsorted array
minIndex = i;
for (j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the first element


swap(&arr[minIndex], &arr[i]);
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

selectionSort(arr, size);

printf("Sorted array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 64 25 12 22 11
Sorted array: 11 12 22 25 64
Exp 05 : Program for Insertion Sort

Program: Here's the Insertion Sort program in C with output:


#include <stdio.h>

void insertionSort(int arr[], int size) {


int i, key, j;
for (i = 1; i < size; i++) {
key = arr[i];
j = i - 1;

// Move elements of arr[0..i-1] that are greater than key to one position
ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

int main() {
int arr[] = {12, 11, 13, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

insertionSort(arr, size);

printf("Sorted array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 12 11 13 5 6
Sorted array: 5 6 11 12 13
Exp 06 : Program for Quick Sort.

Program:Here's a simple implementation of Quick Sort in C with output:


#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

// Recursively sort elements before and after partition


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

quickSort(arr, 0, size - 1);

printf("Sorted array: ");


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:

Original array: 10 7 8 9 1 5
Sorted array: 1 5 7 8 9 10
Exp 07 : Find Minimum Spanning Tree using Kruskal’s
Algorithm.

Algorithm: Below are the steps for finding MST using Kruskal’s algorithm:

1. Sort all the edges in non-decreasing order of their weight.


2. Pick the smallest edge. Check if it forms a cycle with the spanning tree
formed so far. If the cycle is not formed, include this edge. Else, discard it.
3. Repeat step#2 until there are (V-1) edges in the spanning tree.

Illustration: Below is the illustration of the above approach:


Kruskal’s Minimum Spanning Tree Algorithm

The graph contains 9 vertices and 14 edges. So, the minimum spanning tree
formed will be having (9 – 1) = 8 edges.
After sorting:

Weight Source Destination


1 7 6
2 8 2
2 6 5
4 0 1
4 2 5
6 8 6
7 2 3
7 7 8
8 0 7
8 1 2
9 3 4
10 5 4
11 1 7
14 3 5
Now pick all edges one by one from the sorted list of edges

Step 1: Pick edge 7-6. No cycle is formed, include it.

Step 2: Pick edge 8-2. No cycle is formed, include it.

Step 3: Pick edge 6-5. No cycle is formed, include it.


Step 4: Pick edge 0-1. No cycle is formed, include it.

Step 5: Pick edge 2-5. No cycle is formed, include it.

Step 6: Pick edge 8-6. Since including this edge results in the cycle, discard it.
Pick edge 2-3: No cycle is formed, include it.
Step 7: Pick edge 7-8. Since including this edge results in the cycle, discard it.
Pick edge 0-7. No cycle is formed, include it.

Step 8: Pick edge 1-2. Since including this edge results in the cycle, discard it.
Pick edge 3-4. No cycle is formed, include it.

Note: Since the number of edges included in the MST equals to (V – 1), so the
algorithm stops here
Exp 08 : Find Minimum Cost Spanning Tree of a given
undirected graph using Prim’s algorithm.

Algorithm:The working of Prim’s algorithm can be described by using the


following steps:

Step 1: Determine an arbitrary vertex as the starting vertex of the MST.


Step 2: Follow steps 3 to 5 till there are vertices that are not included in the MST
(known as fringe vertex).
Step 3: Find edges connecting any tree vertex with the fringe vertices.
Step 4: Find the minimum among these edges.
Step 5: Add the chosen edge to the MST if it does not form any cycle.
Step 6: Return the MST and exit

Note: For determining a cycle, we can divide the vertices into two sets [one set
contains the vertices included in MST and the other contains the fringe vertices.]

Illustration:Consider the following graph as an example for which we need to


find the Minimum Spanning Tree (MST).

Step 1: Firstly, we select an arbitrary vertex that acts as the starting vertex of the
Minimum Spanning Tree. Here we have selected vertex 0 as the starting vertex.
Step 2: All the edges connecting the incomplete MST and other vertices are the
edges {0, 1} and {0, 7}. Between these two the edge with minimum weight is {0,
1}. So include the edge and vertex 1 in the MST.

Step 3: The edges connecting the incomplete MST to other vertices are {0, 7},
{1, 7} and {1, 2}. Among these edges the minimum weight is 8 which is of the
edges {0, 7} and {1, 2}. Let us here include the edge {0, 7} and the vertex 7 in
the MST. [We could have also included edge {1, 2} and vertex 2 in the MST].

Step 4: The edges that connect the incomplete MST with the fringe vertices are
{1, 2}, {7, 6} and {7, 8}. Add the edge {7, 6} and the vertex 6 in the MST as it
has the least weight (i.e., 1).
Step 5: The connecting edges now are {7, 8}, {1, 2}, {6, 8} and {6, 5}. Include
edge {6, 5} and vertex 5 in the MST as the edge has the minimum weight (i.e., 2)
among them.

Step 6: Among the current connecting edges, the edge {5, 2} has the minimum
weight. So include that edge and the vertex 2 in the MST.

Step 7: The connecting edges between the incomplete MST and the other edges
are {2, 8}, {2, 3}, {5, 3} and {5, 4}. The edge with minimum weight is edge {2,
8} which has weight 2. So include this edge and the vertex 8 in the MST.
Step 8: See here that the edges {7, 8} and {2, 3} both have same weight which
are minimum. But 7 is already part of MST. So we will consider the edge {2, 3}
and include that edge and vertex 3 in the MST.

Step 9: Only the vertex 4 remains to be included. The minimum weighted edge
from the incomplete MST to 4 is {3, 4}.

The final structure of the MST is as follows and the weight of the edges of the
MST is (4 + 8 + 1 + 2 + 4 + 2 + 7 + 9) = 37.
Note: If we had selected the edge {1, 2} in the third step then the MST would
look like the following.
Exp 09 : Implement N Queen Problem using Backtracking

Problem : 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

Implementation : Follow the steps mentioned below to implement the idea:

1. Start in the leftmost column


2. If all queens are placed return true
3. Try all rows in the current column. Do the following for every row.
i. If the queen can be placed safely in this row
a. Then mark this [row, column] as part of the solution and
recursively check if placing queen here leads to a solution.
b. If placing the queen in [row, column] leads to a solution then
return true.
c. If placing queen doesn’t lead to a solution then unmark this [row,
column] then backtrack and try other rows.
ii. If all rows have been tried and valid solution is not found return false to
trigger backtracking.

Using Backtracking : Below is the recursive tree of the above approach


Exp 10 : From a given vertex in a weighted connected graph,
find shortest paths to other vertices using Dijkstra's algorithm.

Algorithm:
1. Create a set sptSet (shortest path tree set) that keeps track of vertices included
in the shortest path tree, i.e., whose minimum distance from the source is
calculated and finalized. Initially, this set is empty.

2. Assign a distance value to all vertices in the input graph. Initialize all distance
values as INFINITE.
Assign the distance value as 0 for the source vertex so that it is picked first.

3. While sptSet doesn’t include all vertices


I. Pick a vertex u that is not there in sptSet and has a minimum distance
value.
II. Include u to sptSet.
III. Then update the distance value of all adjacent vertices of u.
i. To update the distance values, iterate through all adjacent vertices.
ii. For every adjacent vertex v, if the sum of the distance value of u
(from source) and weight of edge u-v, is less than the distance value
of v, then update the distance value of v.

Note: We use a boolean array sptSet[] to represent the set of vertices included in
SPT. If a value sptSet[v] is true, then vertex v is included in SPT, otherwise not.
Array dist[] is used to store the shortest distance values of all vertices.

Illustration :
To understand the Dijkstra’s Algorithm lets take a graph and find the shortest
path from source to all nodes.

Consider below graph and src = 0


Step 1:
1. The set sptSet is initially empty and distances assigned to vertices are {0,
INF, INF, INF, INF, INF, INF, INF} where INF indicates infinite.
2. Now pick the vertex with a minimum distance value. The vertex 0 is picked,
include it in sptSet. So sptSet becomes {0}. After including 0 to sptSet,
update distance values of its adjacent vertices.
3. Adjacent vertices of 0 are 1 and 7. The distance values of 1 and 7 are
updated as 4 and 8.

The following subgraph shows vertices and their distance values, only the
vertices with finite distance values are shown. The vertices included in SPT are
shown in green colour.

Step 2:
1. Pick the vertex with minimum distance value and not already included in
SPT (not in sptSET). The vertex 1 is picked and added to sptSet.
2. So sptSet now becomes {0, 1}. Update the distance values of adjacent
vertices of 1.
3. The distance value of vertex 2 becomes 12.
Step 3:
1. Pick the vertex with minimum distance value and not already included in
SPT (not in sptSET). Vertex 7 is picked. So sptSet now becomes {0, 1, 7}.
2. Update the distance values of adjacent vertices of 7. The distance value of
vertex 6 and 8 becomes finite (15 and 9 respectively).

Step 4:
1. Pick the vertex with minimum distance value and not already included in
SPT (not in sptSET). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}.
2. Update the distance values of adjacent vertices of 6. The distance value of
vertex 5 and 8 are updated.

We repeat the above steps until sptSet includes all vertices of the given graph.
Finally, we get the following Shortest Path Tree (SPT).

You might also like