0% found this document useful (0 votes)
18 views40 pages

Wa0003

This document is a practical file for the Design and Analysis of Algorithms course submitted by Deepak Negi at Jagan Institute of Management Studies. It includes acknowledgments, a certificate of authenticity, an index of practicals performed, and detailed implementations of various algorithms such as sorting, searching, and graph algorithms. The document serves as a comprehensive report of the student's work and findings in the subject during the academic year 2022-2024.

Uploaded by

Lakshya Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views40 pages

Wa0003

This document is a practical file for the Design and Analysis of Algorithms course submitted by Deepak Negi at Jagan Institute of Management Studies. It includes acknowledgments, a certificate of authenticity, an index of practicals performed, and detailed implementations of various algorithms such as sorting, searching, and graph algorithms. The document serves as a comprehensive report of the student's work and findings in the subject during the academic year 2022-2024.

Uploaded by

Lakshya Pal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

JAGAN INSTITUTE OF MANAGEMENT STUDIES

SECTOR – 5, ROHINI, NEW DELHI

(Affiliated to)

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY

SECTOR – 16 C, DWARKA, NEW DELHI

DESIGN AND ANALYSIS OF ALGORITHM PRACTICAL FILE

Submitted To: Submitted By:


Dr. Chetna Laroiya Deepak negi
MCA-1st SHIFT
Professor(IT) 07214004423
ACKNOWLEDGEMENT

I take this opportunity to give my vote of thanks to my guide who really helped
me throughout this practical that has led to successful and satisfactory
completion of this practical report.

I feel great sense of gratitude for Dr. Chetna Laroiya under whose guidance and
motivation this work has been performed.
I would also like to express my thanks to all lab assistants for giving me
opportunity to work under their esteemed guidance. This practical could not
have been completed without their guidance and coordination.
The inspiration of the faculty members of the Information Technology
Department of JIMS Rohini (Sec-5) enabled me to make a thorough practical
report of these topics.

NAME: DEEPAK NEGI

ENROLLMENT NO: 07214004423

Deepak Negi 07214004423


CERTIFICATE

This is certified to be the bonafide work of the student DEEPAK NEGI,


Enrollment No: 07214004423 for the purpose of subject Design and Analysis of
Algorithm, MCA, 3rd semester under the supervision of Dr. Chetna Laroiya for
the academic year 2022-2024.

Dr. Chetna Laroiya

Associate Professor

JIMS, Rohini

Deepak Negi 07214004423


INDEX

S.NO PRACTICAL DATE SIGN


1 WAP to implement Insertion sort for worst, best and
average case analysis.

2 Selection sort for worst, best and average case analysis.

3 Quick sort for worst and average case analysis

4 Merge sort for worst and average case analysis

5 Binary search for worst and best case analysis

6 WAP to implement Matrix Chain Multiplication of 6


matrices.

7 WAP to implementation a MIN heap from the given set


of values
8 Radix sort to sort numbers up-to 4 digits only.

9 WAP to implement Dijkastra algorithm which finds cost


of shortest path between given nodes.

10 WAP to implement Prims or Kruskal algorithm for


Minimal Spanning Tree.

11 WAP to implement Huffman encoding scheme for special


characters.
12 WAP to implement Naive string matching algorithm.

13 WAP to implement Rabin Karp string matching algorithm


and compare complexity with Naïve algorithm.

Deepak Negi 07214004423


Q1. WAP to implement Insertion sort for worst, best and average case analysis
Code:

#include <stdio.h>

void insertion_sort(int arr[], int n){

int count=0; 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;

count++;

arr[j+1] = key; count++;

printf("The total number of comparisions are %d", count);

printf("\n");

void printArr(int arr[], int n){

for(int i=0; i<n; i++){ printf("%d",

arr[i]);

printf(" ");}

Deepak Negi 07214004423


int main(void)

int n;

printf("Enter the size of array: ");

scanf("%d", &n);

int arr[n];

printf("Enter the elements: ");

for(int i=0; i<n; i++){

scanf("%d", &arr[i]); }

insertion_sort(arr, n);

printf("Sorted array: ");

printArr(arr, n);

return 0;

Output:

Best case (Sorted array)

Worst Case (Reverse sorted array)

Deepak Negi 07214004423


Average Case

Number of elements 5 10 20

Worst 14 54 209

Best 4 9 19

Average 7 15 73

Deepak Negi 07214004423


Q2. Selection sort for worst, best and avg case analysis
Code:

#include <stdio.h>

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

*yp = temp;

void selection_sort(int arr[], int n){

int count=0; for(int i=0; i<n; i++){

int mini = i; int mine = arr[i];

for(int j=i+1; j<n; j++){

count++;

if(mine>arr[j]){

mini=j;

mine=arr[j];

Deepak Negi 07214004423


if(mini != i){ swap(&arr[mini],

&arr[i]);

printf("The total number of comparisions is %d", count);

printf("\n");

void printArr(int arr[], int n){

for(int i=0; i<n; i++){ printf("%d",

arr[i]);

printf(" ");

int main(void) { int n;

printf("Enter the size of array:

"); scanf("%d", &n);

int arr[n];

printf("Enter the elements: ");

for(int i=0; i<n; i++){

scanf("%d", &arr[i]);

Deepak Negi 07214004423


printf("Sorted array:

"); printArr(arr, n);

return 0;

Output:

Best Case

Worst Case

Average Case

Number of elements 5 10 20

Worst 10 45 190

Best 10 45 190

Average 10 45 190

Deepak Negi 07214004423


Q3. Quick sort for worst and avg case analysis
Code:

#include <stdio.h>

void swap(int *xp, int *yp)

int temp = *xp;

*xp = *yp;

*yp = temp;

int partition(int arr[], int p, int r){ int

pivot = arr[r];

int i=p-1;

for(int j=p; j<=r-1; j++){

if(arr[j]<=pivot){

i=i+1;

swap(&arr[i], &arr[j]);

swap(&arr[i+1], &arr[r]);

return i+1;

Deepak Negi 07214004423


int count=0; void quicksort(int

arr[], int p, int r){ if(p<r){

int q = partition(arr, p, r);

count++; quicksort(arr, p,

q-1); quicksort(arr, q+1,

r);

void printArr(int arr[], int n){

for(int i=0; i<n; i++){ printf("%d",

arr[i]);

printf(" ");

printf("\n");

printf("Number of times it is called: %d", count);

int main() { int n; printf("Enter

the size of array: "); scanf("%d",

&n);

int arr[n];

Deepak Negi 07214004423


printf("Enter the elements: ");

for(int i=0; i<n; i++){

scanf("%d", &arr[i]);

}
quicksort(arr, 0, n-1);

printf("Sorted array: ");

printArr(arr, n);

return 0;

Output:

Average Case

Worst Case

Number of elements 5 10 20

Worst 4 9 19

Best 3 6 12

Average 3 7 12

Deepak Negi 07214004423


Q4. Merge sort for worst and avg case analysis
Code:

#include <stdio.h>

void merge(int arr[], int s, int e)

int mid = (s+e)/2; int

len1 = mid-s+1; int

len2 = e-mid; int

arr1[len1]; int

arr2[len2]; int k = s;

for(int i=0; i<len1; i++){

arr1[i] = arr[k++];

k = mid+1;

for(int i=0; i<len2; i++){

arr2[i] = arr[k++];

int index1 = 0;

int index2 = 0;

k = s;

Deepak Negi 07214004423


while(index1<len1 && index2<len2){

if(arr1[index1] < arr2[index2]){

arr[k++] = arr1[index1++];

else{

arr[k++] = arr2[index2++];

while(index1 < len1){ arr[k++]

= arr1[index1++];

while(index2 < len2){ arr[k++]

= arr2[index2++];

int count=0;

void mergeSort(int arr[], int s, int e)

if(s >= e){ return;

Deepak Negi 07214004423


int mid = (s+e)/2;

count++; mergeSort(arr,

s, mid); count++;

mergeSort(arr, mid+1, e);

merge(arr, s, e);

void printArr(int arr[], int n)

for(int i=0; i<n; i++){

printf("%d", arr[i]); printf("

printf("\n");

printf("Number of times it is called: %d", count);


{

int n;

printf("Enter the size of array: ");

scanf("%d", &n);

int arr[n];
printf("Enter the elements: ");

for(int i=0; i<n; i++){

scanf("%d", &arr[i]);

Deepak Negi 07214004423


mergeSort(arr, 0, n-1);

printf("Sorted array: ");

printArr(arr, n);

return 0;

Output:

Worst Case

Average Case

Number of elements 5 10 20

Worst 8 18 38

Best 8 18 38

Average 8 18 38

Deepak Negi 07214004423


Q5. Binary search for worst and best case analysis
Code:

#include <stdio.h> int count = 0; int

binarySearch(int array[], int x, int low, int high) {

while (low <= high) {

count++;

int mid = low + (high - low) / 2; if

(array[mid] == x)

return mid;

if (array[mid] < x)

low = mid + 1;

else

high = mid - 1;

return -1;

int main(){ int n; printf("Enter the

size of array: "); scanf("%d", &n);

int array[n];

printf("Enter the elements: ");


for(int i=0; i<n; i++){ scanf("%d", &array[i]); } int

x; printf("Enter the element you want to search:

Deepak Negi 07214004423


"); scanf("%d", &x); int found =

binarySearch(array, x, 0, n-1); printf("Element

fount at location: %d", found); printf("\n");

printf("Number of iterations: %d", count); }

Output:

Best Case (middle of array)

Worst Case (end of array)

Number of elements 5 10 20

Worst 3 4 5

Best 1 1 1

Average 2 3 4

Deepak Negi 07214004423


Q6. WAP to implement Matrix Chain Multiplication of 6 matrices
Equation: {min {M [i, k] + M [k+1, j] + di-1 dk dj } where i <= k< j

Code:

#include<stdio.h> #include<limits.h>

int MatrixChainMultiplication(int p[], int n)

int m[n][n];

int i, j, k, L, q; for

(i=1; i<n; i++)

m[i][i] = 0;

for (L=2; L<n; L++)

for (i=1; i<n-L+1; i++)

{
j = i+L-1;

m[i][j] = INT_MAX;

for (k=i; k<=j-1; k++)

q = m[i][k] + m[k+1][j] + p[i-1]*p[k]*p[j];

ifq < m[i][j])

Deepak Negi 07214004423


{
m[i][j] = q;
}
}
}
}
return m[1][n-1];
}
int main()
{
int n,i;
printf("Enter number of matrices\n"); scanf("%d",&n);

n++;
int arr[n];
printf("Enter dimensions \n"); for(i=0;i<n;i++)

{
printf("Enter d%d :: ",i);
scanf("%d",&arr[i]);
}
int size = sizeof(arr)/sizeof(arr[0]);
printf("Minimum number of multiplications is %d ", MatrixChainMultiplication(arr, size));

return 0;

}
Output:

Deepak Negi 07214004423


Q7. WAP to implementation a MIN heap from the given set of values
Code:

#include <stdio.h> #include

<conio.h> void min_heap(int *a,

int m, int n){

int j, t;

t= a[m];

j = 2 * m; while (j <= n) { if

(j < n && a[j+1] < a[j]) j = j

+ 1; if (t < a[j])

break;

else if (t >= a[j]) {

a[j/2] = a[j]; j

= 2 * j; }

a[j/2] = t;

return;

void build_minheap(int *a, int n) {

int k;

for(k = n/2; k >= 1; k--) {

min_heap(a,k,n);
}}

Deepak Negi 07214004423


int main() { int

n, i;

printf("Enter number of elements in array: \n"); scanf("%d",&n);

int a[30];

for (i = 1; i <= n; i++) { printf("Enter

elememt:", i);

scanf("%d",&a[i]);

build_minheap(a, n); printf("Min

Heap \n");

for (i = 1; i <= n; i++) {

printf("%d \n",a[i]);}

getch();}

Output:

Deepak Negi 07214004423


Q8. Radix sort to sort numbers up-to 4 digits only.
Code:

#include <stdio.h>

int getMax(int arr[], int n)

int mx = arr[0];

for (int i = 1; i < n; i++)

if (arr[i] > mx) mx =

arr[i]; return mx;

void countSort(int arr[], int n, int exp)

int output[n];

int i, count[10] = { 0 }; for (i = 0; i < n; i++)

count[(arr[i] / exp) % 10]++; for (i = 1; i < 10;

i++) count[i] += count[i - 1]; for (i = n - 1; i >=

0; i--) { output[count[(arr[i] / exp) % 10] - 1] =

arr[i]; count[(arr[i] / exp) % 10]--;

}
for (i = 0; i < n; i++) arr[i]

= output[i];

Deepak Negi 07214004423


void radixsort(int arr[], int n)

int m = getMax(arr, n);

for (int exp = 1; m / exp > 0; exp *= 10)

countSort(arr, n, exp);

void print(int arr[], int n)

for (int i = 0; i < n; i++) printf("%d

", arr[i]);

int main()

int n;

printf("Enter number of element in array: \n"); scanf("%d",

&n);

int arr[n];

printf("Enter element: \n");

for(int i=0; i<n; i++){

scanf("%d", &arr[i]);

Deepak Negi 07214004423


}
printf("Original array: \n");

for(int i=0; i<n; i++){

printf("%d ", arr[i]);

radixsort(arr, n);

printf("\n");

printf("Sorted array: \n");

print(arr, n);

return 0;

Output:

Deepak Negi 07214004423


Q9. WAP to implement Dijkastra algorithm with finds cost of shortest path
between given nodes.
Code:

#include <stdio.h>

#define INFINITY 9999

#define MAX 10

void Dijkstra(int Graph[MAX][MAX], int n, int start);

void Dijkstra(int Graph[MAX][MAX], int n, int start) {

int cost[MAX][MAX], distance[MAX], pred[MAX];

int visited[MAX], count, mindistance, nextnode, i, j;

// Creating cost matrix for

(i = 0; i < n; i++) for (j = 0; j

< n; j++) if (Graph[i][j] ==

0) cost[i][j] = INFINITY;

else cost[i][j] = Graph[i][j];

for (i = 0; i < n; i++) {

distance[i] = cost[start][i];

pred[i] = start;

visited[i] = 0;

distance[start] = 0;
visited[start] = 1;

count = 1;

Deepak Negi 07214004423


while (count < n - 1) { mindistance

= INFINITY;

for (i = 0; i < n; i++) if (distance[i] <

mindistance && !visited[i]) { mindistance =

distance[i];

nextnode = i;

visited[nextnode] = 1;

for (i = 0; i < n; i++)

if (!visited[i])

if (mindistance + cost[nextnode][i] < distance[i]) {

distance[i] = mindistance + cost[nextnode][i];

pred[i] = nextnode;

printf("\nDistance from source to %d: %d", i, distance[i]);

}
int main() {

int Graph[MAX][MAX], i, j, n, u;

printf("Enter the value of n: ");

scanf("%d", &n); printf("Enter

Deepak Negi 07214004423


the graph: \n"); for(i=0; i<n;

i++){ for(j=0; j<n; j++){

printf("Enter: "); scanf("%d",

&Graph[i][j]);

u = 0;

Dijkstra(Graph, n, u);

return 0;

Output:

Deepak Negi 07214004423


Q10. WAP to implement Prims or Kruskal algorithm for Minimal Spanning Tree.
Code:

#include <stdio.h>

#include<stdio.h>

#include<stdbool.h>

#define INF 9999999

#define V 5 int

G[V][V] = {

{0, 9, 75, 0, 0},

{9, 0, 95, 19, 42},

{75, 95, 0, 51, 66},

{0, 19, 51, 0, 31},

{0, 42, 66, 31, 0}};

int main() { int

no_edge;

int selected[V];

memset(selected, false, sizeof(selected));

no_edge = 0; selected[0] = true; int x; int

y;

Deepak Negi 07214004423


printf("Edge : Weight\n");

while (no_edge < V - 1) { int

min = INF; x = 0;

y = 0;

for (int i = 0; i < V; i++) {

if (selected[i]) {

for (int j = 0; j < V; j++) {

if (!selected[j] && G[i][j])

{ if (min > G[i][j]) { min =

G[i][j]; x = i;

y = j ;}

printf("%d - %d : %d\n", x, y, G[x][y]);

selected[y] = true; no_edge++; } return

0;} Output:

Deepak Negi 07214004423


Q11. WAP to implement Huffman encoding scheme for special characters.
Code:

#include <stdio.h>

#include <stdlib.h>

#define MAX_TREE_HT 100

struct MinHeapNode { char

data; unsigned freq;

struct MinHeapNode *left, *right;

};

struct MinHeap {

unsigned size;

unsigned capacity;

struct MinHeapNode **array;

};

struct MinHeapNode *newNode(char data, unsigned freq) {

struct MinHeapNode *temp =

(struct MinHeapNode *)malloc(sizeof(struct MinHeapNode));

temp->left = temp->right = NULL; temp->data = data; temp-

>freq = freq; return temp;

}
struct MinHeap *createMinHeap(unsigned capacity) {

struct MinHeap *minHeap = (struct MinHeap *)malloc(sizeof(struct

MinHeap)); minHeap->size = 0;

Deepak Negi 07214004423


minHeap->capacity = capacity;

minHeap->array = (struct MinHeapNode **)malloc(minHeap->capacity *


sizeof(struct MinHeapNode *));

return minHeap;

void swapMinHeapNode(struct MinHeapNode **a, struct MinHeapNode **b) {

struct MinHeapNode *t = *a;

*a = *b;

*b = t;

void minHeapify(struct MinHeap *minHeap, int idx) {

int smallest = idx; int left = 2 * idx + 1; int right = 2 *

idx + 2;

if (left < minHeap->size &&

minHeap->array[left]->freq < minHeap->array[smallest]->freq)

smallest = left;

if (right < minHeap->size &&

minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest

= right;

if (smallest != idx) {

swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);

minHeapify(minHeap, smallest);

Deepak Negi 07214004423


}

int isSizeOne(struct MinHeap *minHeap) { return (minHeap->size == 1); }

struct MinHeapNode *extractMin(struct MinHeap *minHeap) { struct

MinHeapNode *temp = minHeap->array[0]; minHeap->array[0] =

minHeap->array[minHeap->size - 1];

--minHeap->size;

minHeapify(minHeap, 0);

return temp;

void insertMinHeap(struct MinHeap *minHeap, struct MinHeapNode *minHeapNode) {

++minHeap->size;

int i = minHeap->size - 1;

while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) {

minHeap->array[i] = minHeap->array[(i - 1) / 2];

i = (i - 1) / 2;

minHeap->array[i] = minHeapNode;

void buildMinHeap(struct MinHeap *minHeap)


{

Deepak Negi 07214004423


int n = minHeap->size - 1;

int i; for (i = (n - 1) / 2; i >=

0; --i)

minHeapify(minHeap, i);

void printArr(int arr[], int n) {

int i; for (i = 0; i <

n; ++i) printf("%d",

arr[i]);

printf("\n");

int isLeaf(struct MinHeapNode *root) { return !(root->left) && !(root->right); }

struct MinHeap *createAndBuildMinHeap(char data[], int freq[], int size) { struct

MinHeap *minHeap = createMinHeap(size);

for (int i = 0; i < size; ++i)

minHeap->array[i] = newNode(data[i],

freq[i]); minHeap->size = size;

buildMinHeap(minHeap); return minHeap;

struct MinHeapNode *buildHuffmanTree(char data[], int freq[], int size) {

struct MinHeapNode *left, *right, *top;

struct MinHeap *minHeap = createAndBuildMinHeap(data, freq, size);

while (!isSizeOne(minHeap)) { left = extractMin(minHeap); right =

Deepak Negi 07214004423


extractMin(minHeap); top = newNode('$', left->freq + right->freq);

top->left = left; top->right = right; insertMinHeap(minHeap, top);

return extractMin(minHeap);

void printCodes(struct MinHeapNode *root, int arr[], int top) { if

(root->left) {

arr[top] = 0;

printCodes(root->left, arr, top + 1);

if (root->right) { arr[top]

= 1;

printCodes(root->right, arr, top + 1);

if (isLeaf(root)) {

printf("%c: ", root->data);

printArr(arr, top);

}
}

void HuffmanCodes(char data[], int freq[], int size) {

struct MinHeapNode *root = buildHuffmanTree(data, freq, size);

int arr[MAX_TREE_HT], top = 0;

Deepak Negi 07214004423


printCodes(root, arr, top);

int main() {

char arr[] = {'A', 'B', 'C', 'D'};

int freq[] = {5, 1, 6, 3};

int size = sizeof(arr) / sizeof(arr[0]);

printf(" Char | Huffman code ");

printf("\n \n");

HuffmanCodes(arr, freq, size); return

0;

Output:

Deepak Negi 07214004423


Q12. WAP to implement Naive string matching algorithm.
Code:
#include <stdio.h> #include

<string.h>

void search(char* pat, char* txt)


{
int M = strlen(pat); int

N = strlen(txt);

for (int i = 0; i <= N - M; i++)


{
int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])

break;

if (j== M)
printf("Pattern found at index %d \n", i);
}
}
int main()
{
char txt[] = "XYZXYZXYZXXXYZXYZZY";
char pat[] = "XYZX";

search(pat, txt); retrn 0;

}
Output:

Deepak Negi 07214004423


Q13. WAP to implement Rabin Karp string matching algorithm and compare
complexity with Naïve algorithm.
Code:

#include <stdio.h>

#include <string.h> #define

d 256

void search(char pat[], char txt[], int q)

int M = strlen(pat); int

N = strlen(txt);

int i, j; int p = 0; int t =

0; int h = 1; for (i = 0; i

< M - 1; i++) h = (h * d)

% q;

for (i = 0; i < M; i++) {

p = (d * p + pat[i]) % q; t

= (d * t + txt[i]) % q;

for (i = 0; i <= N - M; i++) {

if (p == t) { for (j = 0; j <

M; j++) { if (txt[i + j] !=

pat[j])

break;

Deepak Negi 07214004423


}

if (j == M)

printf("Pattern found at index %d \n", i);

if (i < N - M) {

t = (d * (t - txt[i] * h) + txt[i + M]) % q;

if (t < 0)

t = (t + q);

int main(){

char txt[] = "GEEKS FOR GEEKS";

char pat[] = "GEEK";

int q = 101; return 0;}

Output:

Algorithm Best Worst

Naïve string matching O(N) O(N2)

Rabin karp algorithm O(M+N) O(NM)

Deepak Negi 07214004423

You might also like