Daa Lab Manual
Daa Lab Manual
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
Head Of Department:...........................................
INDEX:
PRACTICAL - 1
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:
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 -
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 -
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 -
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 -
Fourth pass
Similarly, after the fourth iteration, the array will be -
INPUT:
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
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:
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.
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.
INPUT:
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
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;
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
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.
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.
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.
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.
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.
INPUT:
#include <stdio.h>
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:
EN.NO: 210303124213
Page: 15 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
PRACTICAL – 2
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
INPUT:
// Heap Sort in C
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
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
// Heap sort
heapify(arr, i, 0);
}
}
// Print an array
int main() {
int arr[] = {1, 12, 9, 5, 6, 10};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(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:
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
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.
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 -
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>
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++;
}
}
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:
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.
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
INPUT:
// Quick sort in C
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
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]);
}
}
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};
printf("Unsorted Array\n");
printArray(data, n);
OUTPUT:
Time Complexity:
EN.NO: 210303124213
Page: 29 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
PRACTICAL – 5
Example:
INPUT:
#include<stdio.h>
#include<stdlib.h>
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)
EN.NO: 210303124213
Page: 32 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
PRACTICAL – 6
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];
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]);
}
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:
EN.NO: 210303124213
Page: 35 NO.210:210303124194
PARUL UNIVERSITY FACULTY OF
ENGINEERING & TECHNOLOGY
Analysis Of Algorithm (203124252) B. Tech. 2ndYear
PRACTICAL – 7
EXAMPLE:
Suppose a weighted graph is -
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 -
Now, the number of edges in the above tree equals the number of vertices minus 1.
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];
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
}
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;
OUTPUT:
COMPLEXITY ANALYSIS:
Worst case time complexity of Kruskal’s Algorithm
= O(ElogV) or O(ElogE)
Analysis-
PRACTICAL – 8
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:
Step-04:
Step-05:
Step-06:
Since all the vertices have been included in the MST, so we stop.
INPUT(IN C++):
#include <iostream>
#include<bits/stdc++.h>
#include <cstring>
using namespace std;
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 visit[V];
for(int i=0;i<V;i++){
visit[i]=false;
}
edge = 0;
visit[0] = true;
//For every vertex in the set S, find the all adjacent vertices
}
}
}
}
cout << x << " ---> " << y << " : " << G[x][y];
cout << endl;
visit[y] = true;
edge++;
}
return 0;
}
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.
= O((E + V)logV)
= O(ElogV)
This time complexity can be improved and reduced to O(E + VlogV) using Fibonacci heap.
PRACTICAL – 9
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
Ï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,
Ïinding ľ(1,5)-
We have,
•i = 1
•j = 5
• (value)i = (value)1 = 3
• (weight)i = (weight)1 = 2
Ïinding ľ(2,1)-
We have,
•i = 2
•j = 1
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3
Ïinding ľ(2,3)-
We have,
•i = 2
•j = 3
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3
Ïinding ľ(2,4)-
We have,
•i = 2
•j = 4
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3
Ïinding ľ(2,5)-
We have,
•i = 2
•j = 5
• (value)i = (value)2 = 4
• (weight)i = (weight)2 = 3
• 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.
INPUT(IN C++):
#include<iostream>
using namespace std;
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++)
{
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.
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)
Remaining 0 adjacent and unvisited nodes are visited, marked, and inserted into the queue.
Step 5)
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
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>
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[]
while(p->next!=NULL)
p=p->next;
p->next=q;
}
}
OUTPUT:
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);
OUTPUT:
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.