0% found this document useful (0 votes)
19 views60 pages

Daa Lab Manual

This document is a laboratory manual for the Design and Analysis of Algorithms course at Parul University, detailing various sorting algorithms and their implementations in C. It includes practical experiments on Bubble Sort, Selection Sort, Insertion Sort, MaxHeapsort, and other algorithms, along with their time complexity analyses. The manual also certifies the completion of laboratory experiments by a student, Ayyannagari Rajasekhar Gowd.

Uploaded by

shaikaaweez3
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)
19 views60 pages

Daa Lab Manual

This document is a laboratory manual for the Design and Analysis of Algorithms course at Parul University, detailing various sorting algorithms and their implementations in C. It includes practical experiments on Bubble Sort, Selection Sort, Insertion Sort, MaxHeapsort, and other algorithms, along with their time complexity analyses. The manual also certifies the completion of laboratory experiments by a student, Ayyannagari Rajasekhar Gowd.

Uploaded by

shaikaaweez3
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/ 60

PARUL UNIVERSITY FACULTY OF

ENGINEERING & TECHNOLOGY

FACULTY OF ENGINEERING AND TECHNOLOGY


BACHELOR OF TECHNOLOGY

DESIGN
AND
ANALYSIS OF
ALGORITHM
(203124252)
4th SEMESTER
COMPUTER SCIENCE & ENGINEERING DEPARTMENT

Laboratory Manual
EN. NO. : 210303124213
Page: 1
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY

CERTIFICATE

This is to certify that Mr. AYYANNAGARI RAJASEKHAR GOWD with

enrolment no. 210303124213 has successfully completed his/her laboratoryexperiments

in the DESIGN AND ANALYSIS OF ALGORITHM from the department of

..CSE-(AI).. during the academic year…2021-2022…

Date of Submission:......................... Staff In charge:...........................

Head Of Department:...........................................

EN. NO. : 210303124213


Page: 2
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY

INDEX:

SR. TITLE PageNo. Performa Marks Sign


nce out of
No. Date
100
1. Implementation and Time analysis of 1-14
Bubble, Selection and Insertion sorting
algorithms for best case, average case &
worst case.
2. Implementation and Time analysis of 15-20
MaxHeapsort algorithm.
3. Implementation and Time analysis of 16-22
Merge Sort algorithms for Best case,
Average case &Worst case using Divide
and Conquer
4. Implementation and Time analysis of Quick 22-24
sortalgorithm for best case, average case &
worst case.

5. Implementation of Inversion Pairs in C 24-28


usingDivide and Conquer Approach

6. Implementation of Fractional 29-31


Knapsackproblem in C.
7. Implementation and Time analysis of Krushkal’s 32-39
Minimum spanning Tree algorithms

8. Implementation and Time analysis of 40-45


Prim’s
Minimum spanning Tree algorithms
9. Write a program to solve 0-1 knapsack 46-52
problem

EN. NO. : 210303124213


Page: 3
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY

10. Implementation and Time analysis of Depth 53-59


First Search (DFS) Graph Traversal and
BreadthFirst Traversal (BFS) Graph
Traversal

EN. NO. : 210303124213


Page: 4
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL - 1

AIM: Implementation and Time analysis of Bubble, Selection and


Insertion sortingalgorithms for best case, average case & worst case.

1. BUBBLE SORT:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
WORKING OF BUBBLE SORT:

Let the elements of array are -

First Pass
Sorting will start from the initial two elements. Let compare them to check which is greater.

Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.

Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like -

Now, compare 32 and 35.

Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.
Now, the comparison will be in between 35 and 10.

Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach at the end of
the array. After first pass, the array will be -

Now, move to the second iteration.

EN. NO. : 210303124213


Page: 5
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

Second Pass
The same process will be followed for second iteration.

Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -

Now, move to the third iteration.

Third Pass
The same process will be followed for third iteration.

Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -

Now, move to the fourth iteration.

Fourth pass
Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.

EN. NO. : 210303124213


Page: 6
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

INPUT:

// C program for implementation of Bubble sort

#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */


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

int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};

EN.NO: 210303124213
Page: 7 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

OUTPUT:

COMPLEXITY ANALYSIS:

Time Complexity:

Case Time Complexity


Best Case O(n)
Average Case O(n2)
Worst Case O(n2)

EN.NO: 210303124213
Page: 8 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

2. SELECTION SORT:

The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.

WORKING OF SELECTION SORT:

Let the elements of array are -

Now, for the first position in the sorted array, the entire array is to be scanned sequentially.

At present, 12 is stored at the first position, after searching the entire array, it is found that 8 is the
smallest value.

So, swap 12 with 8. After the first iteration, 8 will appear at the first position in the sorted array.

For the second position, where 29 is stored presently, we again sequentially scan the rest of the items
of unsorted array. After scanning, we find that 12 is the second lowest element in the array that should
be appeared at second position.

Now, swap 29 with 12. After the second iteration, 12 will appear at the second position in the sorted
array. So, after two iterations, the two smallest values are placed at the beginning in a sorted way.

EN.NO: 210303124213
Page: 9 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
The same process is applied to the rest of the array elements. Now, we are showing a pictorial
representation of the entire sorting process.

Now, the array is completely sorted.

INPUT:

// C program for implementation of selection sort

#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;

EN.NO: 210303124213
Page: 10 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


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

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)

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


printf("\n");
}

int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

OUTPUT:

Time Complexity:

EN.NO: 210303124213
Page: 11 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

Case Time Complexity


Best Case O(n2)
Average Case O(n2)
Worst Case O(n2)

3. INSERTION SORT:

Insertion sort is a simple sorting algorithm that works similar 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 at the correct
position in the sorted part.

WORKING OF INSERTION SORT:


Let the elements of array are -

Initially, the first two elements are compared in insertion sort.

Here, 31 is greater than 12. That means both elements are already in ascending order. So, for now, 12
is stored in a sorted sub-array.

Now, move to the next two elements and compare them.

Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with 25. Along with
swapping, insertion sort will also check it with all elements in the sorted array.

For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the sorted
array remains sorted after swapping.

EN.NO: 210303124213
Page: 12 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

Now, two elements in the sorted array are 12 and 25. Move forward to the next elements that are 31
and 8.

Both 31 and 8 are not sorted. So, swap them.

After swapping, elements 25 and 8 are unsorted.

So, swap them.

Now, elements 12 and 8 are unsorted.

So, swap them too.

Now, the sorted array has three items that are 8, 12 and 25. Move to the next items that are 31 and
32.

Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.

Move to the next elements that are 32 and 17.

EN.NO: 210303124213
Page: 13 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
17 is smaller than 32. So, swap them.

Swapping makes 31 and 17 unsorted. So, swap them too.

Now, swapping makes 25 and 17 unsorted. So, perform swapping again.

Now, the array is completely sorted.

INPUT:

#include <stdio.h>

void insert(int a[], int n)


{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j])


{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n)


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

EN.NO: 210303124213
Page: 14 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");

printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

OUTPUT:

Time Complexity:

Case Time Complexity


Best Case O(n)
Average Case O(n2)
Worst Case O(n2)

EN.NO: 210303124213
Page: 15 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 2

AIM: Implementation and Time analysis of MaxHeapsort algorithm.


WORKING OF HEAP SORT:

First, we have to construct a heap from the given array and convert it into max heap.

After converting the given heap into max heap, the array elements are -

Next, we have to delete the root element (89) from the max heap. To delete this node, we have to
swap it with the last node, i.e. (11). After deleting the root element, we again have to heapify it to
convert it into max heap.

After swapping the array element 89 with 11, and converting the heap into max-heap, the elements
of array are -

In the next step, again, we have to delete the root element (81) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (54). After deleting the root element, we again have
to heapify it to convert it into max heap.

EN.NO: 210303124213
Page: 16 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

After swapping the array element 81 with 54 and converting the heap into max-heap, the elements of
array are -

In the next step, we have to delete the root element (76) from the max heap again. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have to
heapify it to convert it into max heap.

After swapping the array element 76 with 9 and converting the heap into max-heap, the elements of
array are -

In the next step, again we have to delete the root element (54) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (14). After deleting the root element, we again have
to heapify it to convert it into max heap.

After swapping the array element 54 with 14 and converting the heap into max-heap, the elements of
array are -

EN.NO: 210303124213
Page: 17 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
In the next step, again we have to delete the root element (22) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (11). After deleting the root element, we again have
to heapify it to convert it into max heap.

After swapping the array element 22 with 11 and converting the heap into max-heap, the elements of
array are -

In the next step, again we have to delete the root element (14) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have
to heapify it to convert it into max heap.

After swapping the array element 14 with 9 and converting the heap into max-heap, the elements of
array are -

In the next step, again we have to delete the root element (11) from the max heap. To delete this
node, we have to swap it with the last node, i.e. (9). After deleting the root element, we again have to
heapify it to convert it into max heap.

After swapping the array element 11 with 9, the elements of array are -

Now, heap has only one element left. After deleting it, heap will be empty.

EN.NO: 210303124213
Page: 18 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

After completion of sorting, the array elements are -

Now, the array is completely sorted

INPUT:

// Heap Sort in C

#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

void heapify(int arr[], int n, int i)


{
// Find largest among root, left child and right child

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

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

// Swap and continue heapifying if root is not largest

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

EN.NO: 210303124213
Page: 19 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
// Main function to do heap sort

void heapSort(int arr[], int n)


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

// Heap sort

for (int i = n - 1; i >= 0; i--) {


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

// Heapify root element to get highest element at root again

heapify(arr, i, 0);
}
}

// Print an array

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


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

int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);

heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}

EN.NO: 210303124213
Page: 20 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

OUTPUT:

Time Complexity:

Case Time Complexity

Best Case O(n logn)


Average Case O(n log n)
Worst Case O(n log n)

EN.NO: 210303124213
Page: 21 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 3

AIM: Implementation and Time analysis of Merge Sort algorithms for Best case,
Average case & Worst case using Divide and Conquer

Working of Merge sort:


Let the elements of array are -

According to the merge sort, first divide the given array into two equal halves. Merge sort keeps
dividing the list into equal parts until it cannot be further divided.
As there are eight elements in the given array, so it is divided into two arrays of size 4.

Now, again divide these two arrays into halves. As they are of size 4, so divide them into new arrays of
size 2.

Now, again divide these arrays to get the atomic value that cannot be further divided.

Now, combine them in the same manner they were broken.


In combining, first compare the element of each array and then combine them into another array in
sorted order.
So, first compare 12 and 31, both are in sorted positions. Then compare 25 and 8, and in the list of two
values, put 8 first followed by 25. Then compare 32 and 17, sort them and put 17 first followed by 32.
After that, compare 40 and 42, and place them sequentially.

In the next iteration of combining, now compare the arrays with two data values and merge them into
an array of found values in sorted order.

Now, there is a final merging of the arrays. After the final merging of above arrays, the array will look
like -

Now, the array is completely sorted.

EN.NO: 210303124213
Page: 22 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

INPUT:

#include <stdio.h>
#include<stdlib.h>

/* Function to merge the subarrays of a[] */

void merge(int a[], int beg, int mid, int end)


{
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;

int LeftArray[n1], RightArray[n2]; //temporary arrays

/* copy data to temp arrays */

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


LeftArray[i] = a[beg + i];
for (int j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];

i = 0; /* initial index of first sub-array */


j = 0; /* initial index of second sub-array */
k = beg; /* initial index of merged sub-array */

while (i < n1 && j < n2)


{
if(LeftArray[i] <= RightArray[j])
{
a[k] = LeftArray[i];
i++;
}
else
{
a[k] = RightArray[j];
j++;
}
k++;
}

EN.NO: 210303124213
Page: 23 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}

while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}

void mergeSort(int a[], int beg, int end)


{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}

/* Function to print the array */

void printArray(int a[], int n)


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

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");

EN.NO: 210303124213
Page: 24 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
printArray(a, n);
mergeSort(a, 0, n - 1);
printf("After sorting array elements are - \n");
printArray(a, n);
return 0;
}

OUTPUT:

Time Complexity:

Case Time Complexity

Best Case O(n*logn)


Average Case O(n*logn)
Worst Case O(n*logn)

EN.NO: 210303124213
Page: 25 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 4

AIM: Implementation and Time analysis of Quick sortalgorithm for best case,
average case & worst case.

WORKING OF QUICK SORT:

arr[] = {10, 80, 30, 90, 40, 50, 70}


Indexes: 0 1 2 3 4 5 6

low = 0, high = 6, pivot = arr[h] = 70


Initialize index of smaller element, i = -1

Traverse elements from j = low to high-1


j = 0 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])
i=0
arr[] = {10, 80, 30, 90, 40, 50, 70} // No change as i and j
// are same

j = 1 : Since arr[j] > pivot, do nothing


// No change in i and arr[]

j = 2 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])


i=1
arr[] = {10, 30, 80, 90, 40, 50, 70} // We swap 80 and 30

j = 3 : Since arr[j] > pivot, do nothing


// No change in i and arr[]

j = 4 : Since arr[j] <= pivot, do i++ and swap(arr[i], arr[j])


i=2
arr[] = {10, 30, 40, 90, 80, 50, 70} // 80 and 40 Swapped
j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j]
i=3

arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped
We come out of loop because j is now equal to high-1.

EN.NO: 210303124213
Page: 26 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
Finally we place pivot at correct position by swapping
arr[i+1] and arr[high] (or pivot)
arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped

Now 70 is at its correct place. All elements smaller than


70 are before it and all elements greater than 70 are after
it.

INPUT:

// Quick sort in C

#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}

// function to find the partition position

int partition(int array[], int low, int high)


{

// select the rightmost element as pivot


int pivot = array[high];

// pointer for greater element


int i = (low - 1);

// traverse each element of the array


// compare them with the pivot
for (int j = low; j < high; j++)
{
if (array[j] <= pivot)
{

// if element smaller than pivot is found


// swap it with the greater element pointed by i
i++;

EN.NO: 210303124213
Page: 27 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
// swap element at i with element at j
swap(&array[i], &array[j]);
}
}

// swap the pivot element with the greater element at i


swap(&array[i + 1], &array[high]);

// return the partition point


return (i + 1);
}

void quickSort(int array[], int low, int high)


{
if (low < high)
{

// find the pivot element such that


// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);

// recursive call on the left of pivot


quickSort(array, low, pi - 1);

// recursive call on the right of pivot


quickSort(array, pi + 1, high);
}
}

// function to print array elements


void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
}
// main function
int main()

EN.NO: 210303124213
Page: 28 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
{
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);

printf("Unsorted Array\n");
printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}

OUTPUT:

Time Complexity:

Case Time Complexity

Best Case O(n*logn)


Average Case O(n*logn)
Worst Case O(n2)

EN.NO: 210303124213
Page: 29 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 5

AIM: Implementation of Inversion Pairs in C using Divide and Conquer Approach.

Example:

Input: arr[] = {8, 4, 2, 1}


Output: 6
Explanation: Given array has six inversions:
(8, 4), (4, 2), (8, 2), (8, 1), (4, 1), (2, 1).

Input: arr[] = {3, 1, 2}


Output: 2
Explanation: Given array has two inversions:
(3, 1), (3, 2)

INPUT:

#include<stdio.h>
#include<stdlib.h>

int mergesort(int arr[],int l,int r);


int merge(int arr[],int l,int m,int r);
int findinv(int a[], int n)
{
return mergesort(a,0,n);
}

void main()
{
int n,*a,i;
printf("Enter nuber of elements : ");
scanf("%d",&n);
printf("Enter %d elements : ",n);
a=(int*)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Number of inversion = %d",findinv(a,n));

EN.NO: 210303124213
Page: 30 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

//merge
int merge(int arr[],int l,int m,int r)
{
int len,i,j,k,*c,count=0;
len=r-l+1;
c=(int*)malloc(sizeof(int)*len);
i=0;
j=l;
k=m;
while(j<=m-1 && k<=r)
{
if(arr[j]<=arr[k])
{
c[i++]=arr[j++];

}
else
{
c[i++]=arr[k++];
count+=m-j;

while(j<=m-1)
{
c[i++]=arr[j++];
}

while(k<=r)
{
c[i++]=arr[k++];
}
i=0;
while(l<=r)
{
arr[l++]=c[i++];

EN.NO: 210303124213
Page: 31 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
}

return count;
}
//mergesort
int mergesort(int arr[],int l,int r)
{ int count=0;
int m=(l+r)/2;
if(l<r)
{
count+=mergesort(arr,l,m);
count+=mergesort(arr,m+1,r);
count+=merge(arr,l,m+1,r);
}
return count;
}

OUTPUT:

COMPLEXITY ANALYSIS:

Time Complexity: O(n^2), Two nested loops are needed to traverse the array from
start to end, so the Time complexity is O(n^2)

Space Complexity:O(1), No extra space is required

EN.NO: 210303124213
Page: 32 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 6

AIM: Implementation of Fractional Knapsack problem in C.

EXAMPLE:
Input:
Items as (value, weight) pairs
arr[] = {{60, 10}, {100, 20}, {120, 30}}
Knapsack Capacity, W = 50;

Output:
Maximum possible value = 240
by taking items of weight 10 and 20 kg and 2/3 fraction
of 30 kg. Hence total price will be 60+100+(2/3)(120) = 240

INPUT:

#include <stdio.h>

void main()
{
int capacity, no_items, cur_weight, item;
int used[10];
float total_profit;
int i;
int weight[10];
int value[10];

printf("Enter the capacity of knapsack:\n");


scanf("%d", &capacity);
printf("Enter the number of items:\n");
scanf("%d", &no_items);
printf("Enter the weight and value of %d item:\n", no_items);
for (i = 0; i < no_items; i++)

EN.NO: 210303124213
Page: 33 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
{
printf("Weight[%d]:\t", i);
scanf("%d", &weight[i]);
printf("Value[%d]:\t", i);
scanf("%d", &value[i]);
}

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


used[i] = 0;

cur_weight = capacity;
while (cur_weight > 0)
{
item = -1;
for (i = 0; i < no_items; ++i)
if ((used[i] == 0) &&
((item == -1) || ((float) value[i] / weight[i] > (float) value[item] /
weight[item])))
item = i;

used[item] = 1;
cur_weight -= weight[item];
total_profit += value[item];
if (cur_weight >= 0)
printf("Added object %d (%d Rs., %dKg) completely in the bag. Space left:
%d.\n", item + 1, value[item], weight[item], cur_weight);
else
{
int item_percent = (int) ((1 + (float) cur_weight / weight[item]) * 100);
printf("Added %d%% (%d Rs., %dKg) of object %d in the bag.\n",
item_percent, value[item], weight[item], item + 1);
total_profit -= value[item];
total_profit += (1 + (float)cur_weight / weight[item]) * value[item];
}
}

EN.NO: 210303124213
Page: 34 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
printf("Filled the bag with objects worth %.2f Rs.\n", total_profit);
}

OUTPUT:

COMPLEXITY ANALYSIS:

Time Complexity: Time complexity of the sorting + Time complexity of the


loop to maximize profit = O(NlogN) + O(N) = O(NlogN)

Space Complexity: O(1)

EN.NO: 210303124213
Page: 35 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 7

AIM: Implementation and Time analysis of Krushkal’s Minimum spanning Tree


algorithms.

EXAMPLE:
Suppose a weighted graph is -

Step 1 - First, add the edge AB with weight 1 to the MST.

Step 2 - Add the edge DE with weight 2 to the MST as it is not creating the cycle.

Step 3 - Add the edge BC with weight 3 to the MST, as it is not creating any cycle or loop.

EN.NO: 210303124213
Page: 36 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
Step 4 - Now, pick the edge CD with weight 4 to the MST, as it is not forming the cycle.

Step 5 - After that, pick the edge AE with weight 5. Including this edge will create the cycle, so discard
it.

Step 6 - Pick the edge AC with weight 7. Including this edge will create the cycle, so discard it.

Step 7 - Pick the edge AD with weight 10. Including this edge will also create the cycle, so discard it.

So, the final minimum spanning tree obtained from the given weighted graph by using Kruskal's
algorithm is -

The cost of the MST is = AB + DE + BC + CD = 1 + 2 + 3 + 4 = 10.

Now, the number of edges in the above tree equals the number of vertices minus 1.

So, the algorithm stops here.

EN.NO: 210303124213
Page: 37 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

INPUT(IN C++):

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
const int MAX = 1000;
int id[MAX], nodes, edges; //array id is use for check the parent of vertex;
pair <long long, pair<int, int> > p[MAX];

//initialise the parent array id[]


void init()
{
for(int i = 0;i < MAX;++i)
id[i] = i;
}

int root(int x)
{
while(id[x] != x) //if x is not itself parent then update its parent
{
id[x] = id[id[x]];
x = id[x];
}
return x; //return the parent
}

//function for union


void union1(int x, int y)
{
int p = root(x);
int q = root(y);
id[p] = id[q];

EN.NO: 210303124213
Page: 38 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

//function to find out the edges in minimum spanning tree and its cost
long long kruskal(pair<long long, pair<int, int> > p[])
{
int x, y;
long long cost, minimumCost = 0;
for(int i = 0;i < edges;++i)
{
x = p[i].second.first;
y = p[i].second.second;
cost = p[i].first;
if(root(x) != root(y))
{
minimumCost += cost;
cout<<x<<" --- > "<<y<<" :"<<p[i].first<<endl;//print the edges contain in spanning tree
union1(x, y);
}
}
return minimumCost;
}

int main()
{
int x, y;
long long weight, cost, minimumCost;
init();
cout <<"Enter Nodes and edges"<<endl;
cin >> nodes >> edges;

//enter the vertex and cost of edges


for(int i = 0;i < edges;++i)
{
cout<<"Enter the value of X, Y and edges"<<endl;
cin >> x >> y >> weight;
p[i] = make_pair(weight, make_pair(x, y));

EN. NO. : 210303124194


Page: 39
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

//sort the edges according to their cost


sort(p, p + edges);
minimumCost = kruskal(p);
cout <<"Minimum cost is "<< minimumCost << endl;
return 0;
}

OUTPUT:

COMPLEXITY ANALYSIS:
Worst case time complexity of Kruskal’s Algorithm
= O(ElogV) or O(ElogE)

Analysis-

• The edges are maintained as min heap.


• The next edge can be obtained in O(logE) time if graph has E edges.
• Reconstruction of heap takes O(E) time.
• So, Kruskal’s Algorithm takes O(ElogE) time.
• The value of E can be at most O(V2)

EN. NO. : 210303124194


Page: 40
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 8

AIM: Implementation and Time analysis of Prim’s Minimum spanning Tree


algorithms.

EXAMPLE:
Construct the minimum spanning tree (MST) for the given graph using Prim’s Algorithm-

Solution-
The above discussed steps are followed to find the minimum cost spanning tree using Prim’s Algorithm-

Step-01:

Step-02:

Step-03:

EN. NO. : 210303124194


Page: 41
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

Step-04:

Step-05:

Step-06:

Since all the vertices have been included in the MST, so we stop.

Now, Cost of Minimum Spanning Tree


= Sum of all edge weights
= 10 + 25 + 22 + 12 + 16 + 14
= 99 units

EN. NO. : 210303124194


Page: 42
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

INPUT(IN C++):

#include <iostream>
#include<bits/stdc++.h>
#include <cstring>
using namespace std;

// number of vertices in graph


#define V 7

// create a 2d array of size 7x7


//for adjacency matrix to represent graph

int main ()
{
// create a 2d array of size 7x7
//for adjacency matrix to represent graph

int G[V][V] =
{
{0,28,0,0,0,10,0},
{28,0,16,0,0,0,14},
{0,16,0,12,0,0,0},
{0,0,12,22,0,18},
{0,0,0,22,0,25,24},
{10,0,0,0,25,0,0},
{0,14,0,18,24,0,0}
};

int edge; // number of edge

EN. NO. : 210303124194


Page: 43
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

// create an array to check visited vertex

int visit[V];

//initialise the visit array to false

for(int i=0;i<V;i++){
visit[i]=false;
}

// set number of edge to 0

edge = 0;

// the number of edges in minimum spanning tree will be


// always less than (V -1), where V is the number of vertices in
//graph

// choose 0th vertex and make it true

visit[0] = true;

int x; // row number


int y; // col number

// print for edge and weight

cout << "Edge" << " : " << "Weight";


cout << endl;
while (edge < V - 1)
{
//in spanning tree consist the V-1 number of edges

//For every vertex in the set S, find the all adjacent vertices

EN. NO. : 210303124194


Page: 44
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
// , calculate the distance from the vertex selected.
// if the vertex is already visited, discard it otherwise
//choose another vertex nearest to selected vertex.
int min = INT_MAX;
x = 0;
y = 0;

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


if (visit[i]) {
for (int j = 0; j < V; j++) {
if (!visit[j] && G[i][j]) { // not in selected and there is an edge
if (min > G[i][j]) {
min = G[i][j];
x = i;
y = j;
}

}
}
}
}
cout << x << " ---> " << y << " : " << G[x][y];
cout << endl;
visit[y] = true;
edge++;
}

return 0;
}

EN. NO. : 210303124194


Page: 45
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

OUTPUT:

COMPLEXITY ANALYSIS:

• If adjacency list is used to represent the graph, then using breadth first search, all the vertices can be
traversed in O(V + E) time.
• We traverse all the vertices of graph using breadth first search and use a min heap for storing the vertices
not yet included in the MST.
• To get the minimum weight edge, we use min heap as a priority queue.
• Min heap operations like extracting minimum element and decreasing key value takes O(logV) time.

So, overall time complexity


= O(E + V) x O(logV)

= O((E + V)logV)
= O(ElogV)

This time complexity can be improved and reduced to O(E + VlogV) using Fibonacci heap.

EN. NO. : 210303124194


Page: 46
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 9

AIM: Write a program to solve 0-1 knapsack problem.

EXAMPLE:
Find the optimal solution for the 0/1 knapsack problem making use of dynamic programming approach.
Consider-
n=4
w = 5 kg
(w1, w2, w3, w4) = (2, 3, 4, 5)
(b1, b2, b3, b4) = (3, 4, 5, 6)

Solution-
Given-
• Knapsack capacity (w) = 5 kg
• Number of items (n) = 4
Step-01:
• Draw a table say ‘T’ with (n+1) = 4 + 1 = 5 number of rows and (w+1) = 5 + 1 = 6 number of
columns.
• Fill all the boxes of 0th row and 0th column with 0.

Step-02:
Start filling the table row wise top to bottom from left to right using the formula-
T (i , j) = max { T ( i-1 , j ) , valuei + T( i-1 , j – weighti ) }

Ïinding ľ(1,1)-
We have,
•i = 1
•j = 1

EN. NO. : 210303124194


Page: 47
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
• (value)i = (value)1 = 3
• (weight)i = (weight)1 = 2

Substituting the values, we get-


T(1,1) = max { T(1-1 , 1) , 3 + T(1-1 , 1-2) }
T(1,1) = max { T(0,1) , 3 + T(0,-1) }
T(1,1) = T(0,1) { Ignore T(0,-1) }
T(1,1) = 0
Ïinding ľ(1,2)-
We have,
•i = 1
•j = 2
• (value)i = (value)1 = 3
• (weight)i = (weight)1 = 2

Substituting the values, we get-


T(1,2) = max { T(1-1 , 2) , 3 + T(1-1 , 2-2) }
T(1,2) = max { T(0,2) , 3 + T(0,0) }
T(1,2) = max {0 , 3+0}
T(1,2) = 3

Ïinding ľ(1,3)-
We have,
•i = 1
•j = 3
• (value)i = (value)1 = 3
• (weight)i = (weight)1 = 2
Substituting the values, we get-
T(1,3) = max { T(1-1 , 3) , 3 + T(1-1 , 3-2) }
T(1,3) = max { T(0,3) , 3 + T(0,1) }
T(1,3) = max {0 , 3+0}
T(1,3) = 3
Ïinding ľ(1,4)-
We have,

EN. NO. : 210303124194


Page: 48
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
•i = 1
•j = 4
• (value)i = (value)1 = 3
• (weight)i = (weight)1 = 2
Substituting the values, we get-
T(1,4) = max { T(1-1 , 4) , 3 + T(1-1 , 4-2) }
T(1,4) = max { T(0,4) , 3 + T(0,2) }
T(1,4) = max {0 , 3+0}
T(1,4) = 3

Ïinding ľ(1,5)-
We have,
•i = 1
•j = 5
• (value)i = (value)1 = 3

• (weight)i = (weight)1 = 2

Substituting the values, we get-


T(1,5) = max { T(1-1 , 5) , 3 + T(1-1 , 5-2) }
T(1,5) = max { T(0,5) , 3 + T(0,3) }
T(1,5) = max {0 , 3+0}
T(1,5) = 3

Ïinding ľ(2,1)-
We have,
•i = 2
•j = 1
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3

Substituting the values, we get-


T(2,1) = max { T(2-1 , 1) , 4 + T(2-1 , 1-3) }
T(2,1) = max { T(1,1) , 4 + T(1,-2) }
T(2,1) = T(1,1) { Ignore T(1,-2) }
T(2,1) = 0

EN. NO. : 210303124194


Page: 49
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
Ïinding ľ(2,2)-
We have,
•i = 2
•j = 2
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3

Substituting the values, we get-
T(2,2) = max { T(2-1 , 2) , 4 + T(2-1 , 2-3) }
T(2,2) = max { T(1,2) , 4 + T(1,-1) }
T(2,2) = T(1,2) { Ignore T(1,-1) }
T(2,2) = 3

Ïinding ľ(2,3)-
We have,
•i = 2
•j = 3
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3

Substituting the values, we get-


T(2,3) = max { T(2-1 , 3) , 4 + T(2-1 , 3-3) }
T(2,3) = max { T(1,3) , 4 + T(1,0) }
T(2,3) = max { 3 , 4+0 }
T(2,3) = 4

Ïinding ľ(2,4)-
We have,
•i = 2
•j = 4
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3

Substituting the values, we get-


T(2,4) = max { T(2-1 , 4) , 4 + T(2-1 , 4-3) }
T(2,4) = max { T(1,4) , 4 + T(1,1) }

EN. NO. : 210303124194


Page: 50
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
T(2,4) = max { 3 , 4+0 }
T(2,4) = 4

Ïinding ľ(2,5)-
We have,
•i = 2
•j = 5
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3

Substituting the values, we get-


T(2,5) = max { T(2-1 , 5) , 4 + T(2-1 , 5-3) }
T(2,5) = max { T(1,5) , 4 + T(1,2) }
T(2,5) = max { 3 , 4+3 }
T(2,5) = 7
Similarly, compute all the entries.
After all the entries are computed and filled in the table, we get the following table-

• The last entry represents the maximum possible value that can be put into the knapsack.
• So, maximum possible value that can be put into the knapsack = 7.

EN. NO. : 210303124194


Page: 51
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

INPUT(IN C++):

#include<iostream>
using namespace std;

//maximum of two integers

int max(int a, int b)


{
return (a > b) ? a : b;
}

//maximum value that can be put in a knapsack

int knapSack(int W, int wt[], int val[], int n)


{
// Base Case

if (n == 0 || W == 0)
return 0;

if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);

// Return the maximum of two cases: (1) nth item included (2) not included

else
return max(val[n - 1] + knapSack(W - wt[n - 1], wt, val, n - 1),
knapSack(W, wt, val, n - 1));
}

int main()
{
cout << "Enter the number of items in a Knapsack:";
int n, W;
cin >> n;
int val[n], wt[n];
for (int i = 0; i < n; i++)
{

EN. NO. : 210303124194


Page: 52
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
cout << "Enter value and weight for item " << i << ":";
cin >> val[i];
cin >> wt[i];
}

cout << "Enter the capacity of knapsack:";


cin >> W;
cout << knapSack(W, wt, val, n);

return 0;
}

OUTPUT:

COMPLEXITY ANALYSIS:

• Each entry of the table requires constant time θ(1) for its computation.
• It takes θ(nw) time to fill (n+1)(w+1) table entries.
• It takes θ(n) time for tracing the solution since tracing process traces the n rows.
• Thus, overall θ(nw) time is taken to solve 0/1 knapsack problem using dynamic programming.

EN. NO. : 210303124194


Page: 53
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

PRACTICAL – 10

AIM: Implementation and Time analysis of Depth First Search (DFS) Graph
Traversal and Breadth First Traversal (BFS) Graph Traversal.

Example of BFS
Step 1)

You have a graph of seven numbers ranging from 0 – 6.


Step 2)

0 or zero has been marked as a root node.


Step 3)

0 is visited, marked, and inserted into the queue data structure.


Step 4)

EN. NO. : 210303124194


Page: 54
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

Remaining 0 adjacent and unvisited nodes are visited, marked, and inserted into the queue.
Step 5)

Traversing iterations are repeated until all nodes are visited.

Example of DFS
In the following example of DFS, we have used an undirected graph having 5 vertices.

Step 1)

We have started from vertex 0. The algorithm begins by putting it in the visited list and
simultaneously putting all its adjacent vertices in the data structure called stack.
Step 2)

You will visit the element, which is at the top of the stack, for example, 1 and go to its adjacent

EN. NO. : 210303124194


Page: 55
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
nodes. It is because 0 has already been visited. Therefore, we visit vertex 2.
Step 3)

Vertex 2 has an unvisited nearby vertex in 4. Therefore, we add that in the stack and visit it.
Step 4)

Finally, we will visit the last vertex 3, it doesn’t have any unvisited adjoining nodes. We have
completed the traversal of the graph using DFS algorithm.

INPUT(DFS):

#include<stdio.h>
#include<stdlib.h>

typedef struct node


{
struct node *next;
int vertex;
}node;
node *G[20];
//heads of linked list
int visited[20];
int n;
void read_graph();
//create adjacency list
void insert(int,int);
//insert an edge (vi,vj) in te adjacency list
void DFS(int);
void main()
{
int i;
read_graph();

EN. NO. : 210303124194


Page: 56
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
//initialised visited to 0

for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
}
void DFS(int i)
{
node *p;

printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;

if(!visited[i])
DFS(i);
p=p->next;
}
}

void read_graph()
{

int i,vi,vj,no_of_edges;
printf("Enter number of vertices:");

scanf("%d",&n);
//initialise G[] with a null

for(i=0;i<n;i++)
{
G[i]=NULL;
//read edges and insert them in G[]

printf("Enter number of edges:");


scanf("%d",&no_of_edges);
for(i=0;i<no_of_edges;i++)
{
printf("Enter an edge(u,v):");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
}

EN. NO. : 210303124194


Page: 57
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
}
}
void insert(int vi,int vj)
{
node *p,*q;

//acquire memory for the new node


q=(node*)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL;
//insert the node in the linked list number vi
if(G[vi]==NULL)
G[vi]=q;
else
{
//go to end of the linked list
p=G[vi];

while(p->next!=NULL)
p=p->next;
p->next=q;
}
}

OUTPUT:

Complexity of Depth First Search:

EN. NO. : 210303124194


Page: 58
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear

The time complexity of the DFS algorithm is represented in the form of O(V + E), where V is the
number of nodes and E is the number of edges.
The space complexity of the algorithm is O(V).

INPUT(BFS):

#include<stdio.h>
int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;

void bfs(int v) {
for(i = 1; i <= n; i++)
if(a[v][i] && !visited[i])
q[++r] = i;
if(f <= r) {
visited[q[f]] = 1;
bfs(q[f++]);
}
}

void main() {
int v;
printf("\n Enter the number of vertices:");
scanf("%d", &n);

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


q[i] = 0;
visited[i] = 0;
}

printf("\n Enter graph data in matrix form:\n");


for(i=1; i<=n; i++) {
for(j=1;j<=n;j++) {
scanf("%d", &a[i][j]);
}
}

printf("\n Enter the starting vertex:");


scanf("%d", &v);
bfs(v);
printf("\n The node which are reachable are:\n");

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


if(visited[i])
printf("%d\t", i);
else {

EN. NO. : 210303124194


Page: 59
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
printf("\n Bfs is not possible. Not all nodes are reachable");
break;
}
}
}

OUTPUT:

Complexity of Breadth First Search:

The Time complexity of BFS is O(V + E) when Adjacency List is used and O(V^2) when Adjacency Matrix is
used, where V stands for vertices and E stands for edges.

EN. NO. : 210303124194


Page: 60

You might also like