Name of the Student : CHANDRASEKHAR MUPPALA
Batch: 2019-2023 Year: II Semester: IV Section:J
Register No: U19CN154
MARCH 2021
1
Name CHANDRASEKHAR MUPPALA
Programme [Link] Branch Computer Science Engineering
Year 2021 Semester IV
Register No: U19CN154
Certified that this is the bonafide record of work done by the above student in the
Design and Analysis of Algorithm laboratory during the
……………IV………………….Semester in the Academic Year 2019 -2023
Faculty in-charge Head of Department
Submitted for the practical Examination held on 19-06-2021
Internal Examiner. External Examiner
2
DESIGN AND ANALYSICS OF ALGORITHM LAB - U18PCCS4L2
LIST OF EXPERIMENTS
[Link] NAME OF THE EXPERIMENT
Implement recursive algorithms using divide-and-conquer algorithmic techniques to analyze
1A (merge sort)
Implement recursive algorithms using divide-and-conquer algorithmic techniques to analyze
1B (quick sort)
Implement recursive algorithms using divide-and-conquer algorithmic techniques to analyze
1C (binary search)
Implement and analyze greedy method for minimum spanning tree problem.
2
Implement and analyze dynamic programming method for knapsack problem.
3
Implement the graph traversal techniques for depth first search
4
Implement and analyze backtracking method for sum of subsets problem.
5
Implement the branch and bound technique for travelling salesman problem and compare with
6 dynamic programming
7 Implement and analyze randomized algorithm for Hiring Problem
3
CONTENT
[Link] NAME OF THE EXPERIMENT PAGE NO
Implement recursive algorithms using divide-and-conquer algorithmic
1A techniques to analyze (merge sort) 6
Implement recursive algorithms using divide-and-conquer algorithmic
1B techniques to analyze (quick sort) 9
Implement recursive algorithms using divide-and-conquer algorithmic
1C techniques to analyze (binary search) 12
Implement and analyze greedy method for minimum spanning tree problem.
2 14
Implement and analyze dynamic programming method for knapsack problem.
3 17
Implement the graph traversal techniques for depth first search
4 20
Implement and analyze backtracking method for sum of subsets problem.
5 24
Implement the branch and bound technique for travelling salesman problem and
6 compare with dynamic programming 27
30
7 Implement and analyze randomized algorithm for Hiring Problem
4
Ex. No 1a IMPLEMENT RECURSIVE ALGORITHMS USING DIVIDE-AND-CONQUER
ALGORITHMIC TECHNIQUES TO ANALYZE (MERGE SORT)
Aim:
Implement Merge sort algorithm for sorting a list of integers in ascending order.
Algorithm:
STEP 1: Merge sort(A[O .. n - 1])
STEP 2: Sorts array A[O .. n - 1] by recursive mergesort
STEP 3: Input: An array A [O .. n - 1] of orderable elements
STEP 4: Output: Array A [O .. n - 1] sorted in nondecreasing order
STEP 5: Merge (B[O .. p- 1], C[O .. q -1], A[O.. p + q -1])
STEP 6: Merges two sorted arrays into one sorted array
STPE 7: Input: Arrays B [O .. p -1] and C[O .. q -1] both sorted
STEP 8: Output: Sorted array A [O .. p + q -1] of the elements of Band C
Program:
#include<stdio.h>
#include<conio.h>
int a[200]; int
ms(int,int); int
merge(int,int,int);
void main()
{
int n,i;
printf("Enter the value of n:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
printf("a[%d]=",i);
5
scanf("%d",&a[i]);
}
ms(1,n);
printf("Elements after Sorting:"); for(i=1;i<=n;i++)
{
printf("\na[%d]=%d",i,a[i]);
} } int ms(int
l,int k) { int m;
if(l<k)
{
m=(l+k)/2;
ms(l,m);
ms(m+1,k);
merge(l,m,k);
}
}
int merge(l,m,k) { int
i,h,j,b[500],x; i=l; h=l;
j=m+1;
while((h<=m)&&(j<=k))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h=h+1; }
else
{
b[i]=a[j];
j=j+1; }
i=i+1;
}
if(h>m)
{
for(x=j;x<=k;x++)
{ b[i]=a[x];
i=i+1; } } else
{
for(x=h;x<=m;x++)
{
b[i]=a[x];
i=i+1; }
}
for(x=l;x<=k;x++)
{
a[x]=b[x];
}
}
6
:
Output
7
Result:
Thus, the Program to sort an array using Merge Sort is implemented and executed successfully.
Ex. No 1b IMPLEMENT RECURSIVE ALGORITHMS USING DIVIDE-AND-CONQUER
ALGORITHMIC TECHNIQUES TO ANALYZE (QUICK SORT)
Aim:
Implement Quick sort algorithm for sorting a list of integers in ascending order.
Algorithm:
STEP 1: Choose the highest index value has pivot
STEP 2: Take two variables to point left and right of the list excluding pivot
STEP3: left points to the low index
STEP 4: right points to the high
STEP 5: while value at left is less than pivot move right
STEP 6: while value at right is greater than pivot move left
STEP 7: if both step 5 and step 6 does not match swap left and right
STEP 8: if left ≥ right, the point where they met is new pivot
Program:
#include<stdio.h>
#include<conio.h>
int a[200]; int
qs(int,int);
int part(int ,int); void
main()
{
int n,i;
printf("Enter the value of n:");
scanf("%d",&n); for
(i=1;i<=n;i++) {
printf("a[%d]=",i);
scanf("%d",&a[i]);
8
}
a[i]=32676;
qs(1,n);
printf("Elements after sorting");
for(i=1;i<=n;i++)
{
printf("\na[%d]=%d",i,a[i]);
}
return 0;
}
int qs(p,q)
{ int j;
if(p<q)
{
j=part(p,q+1);
qs(p,j-1);
qs(j+1,q);
}
} int
part(m,p) {
int v,i,j,t;
v=a[m];
i=m; j=p;
do {
do {
i=i+1;
}
while(a[i]<=v);
do {
j=j-1;
}
while(a[j]>v);
if(i<j) {
t=a[i];
a[i]=a[j];
a[j]=t;
} }
while(i<j);
a[m]=a[j];
a[j]=v;
return j;
9
Output
10
Result:
Thus, the Program to sort an array using Quick Sort is implemented and executed successfully.
Ex. No 1c IMPLEMENT RECURSIVE ALGORITHMS USING DIVIDE-AND-CONQUER
ALGORITHMIC TECHNIQUES TO ANALYZE (Binary Search)
Aim
Implement Binary search algorithm for sorting a list of integers in ascending order.
Algorithm:
STEP: 1 Start with the middle element:
o If the target value is equal to the middle element of the array, then return the index of the
middle element.
o If not, then compare the middle element with the target value,
If the target value is greater than the number in the middle index, then pick the
elements to the right of the middle index, and start with Step 1.
If the target value is less than the number in the middle index, then pick the elements to
the left of the middle index, and start with Step 1.
STEP: 2 When a match is found, return the index of the element matched.
STEP: 3If no match is found, then return -1
Program:
#include <stdio.h> int
main()
{
11
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n"); scanf("%d",
&n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0; last = n - 1;
middle = (first+last)/2;
while (first <= last) { if
(array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break; } else last = middle - 1; middle = (first +
last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0; }
Output:
Enter number of elements
7
Enter 7 integers
-4
5
8
9
11
43
485
Enter the value to find
11
11 found at location 5.
12
Result:
Thus, the Program to sort an array using Binary search is implemented and executed successfully.
Ex. No 2 IMPLEMENT AND ANALYZE GREEDYMETHOD FOR MINIMUM SPANNING
TREE PROBLEM.
Aim:
Implements and analyze minimum spanning tree problem using greedy method.
Algorithm:
STEP 1: Start from any vertex, let us start from vertex 1.
Vertex 3 is connected to vertex 1 with minimum edge cost, hence edge (1, 2) is added to the spanning
tree.
STEP 2: Edge (2, 3) is considered as this is the minimum among edges {(1, 2), (2, 3), (3, 4), (3, 7)}.
STEP 3: We get edge (3, 4) and (2, 4) with minimum cost. Edge (3, 4) is selected at random.
STEP 4: Edges (4, 5), (5, 7), (7, 8), (6, 8) and (6, 9) are selected. As all the vertices are visited, stops.
Program :
#include<stdio.h>
int n,i,temp,j,k,l,cost[10][10],near[10],t[10][10],mincost=0,min=999; void
main()
{
printf("Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter the matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
13
printf("\n cost[%d][%d]=",i,j);
scanf("%d",&cost[i][j]);
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(min>cost[i][j])
{
min=cost[i][j];
k=i;
l=j;
}
}
}
mincost=cost[k][l];
t[1][1]=k; t[1][2]=l;
for(i=1;i<=n;i++)
{
if(cost[i][l]<cost[i][k])
{
near[i]=l; }
else {
near[i]=k;
}
}
near[k]=near[l]=0;
for(i=2;i<=n-1;i++)
{
min=999;
for(j=1;j<=n;j++)
{
if(near[j]!=0)
{
if(min>cost[j][near[j]])
{
min=cost[j][near[j]];
temp=j;
}
}
} j=temp;
t[i][1]=j;t[i][2]=near[j];
mincost=(mincost+cost[j][near[j]]);
near[j]=0;
for(k=1;k<=n;k++)
{
14
if((near[k]!=0)&&(cost[k][near[k]]>cost[k][j]))
near[k]=j;
}
}
mincost=(mincost+cost[j][near[j]]);
printf("\n mincost=%d",mincost);
}
Output:
15
Result:
Thus the program to analyze minimum spanning tree problem using greedy method is executed and output is
verified successfully.
Ex. No 3 IMPLEMENT AND ANALYZE DYNAMIC PROGRAMMING METHOD FOR
KNAPSACK PROBLEM.
Aim:
Implement Dynamic Programming algorithm for the 0/1 Knapsack problem. Algorithm:
STEP 1: In 0-1 Knapsack, items cannot be broken which means the thief should take the item
as a whole or should leave it. This is reason behind calling it as 0-1 Knapsack.
STEP 2: Hence, in case of 0-1 Knapsack, the value of xi can be either 0 or 1, other constraints remains same.
STEP 3: 0-1 Knapsack cannot be solved by Greedy [Link] approach may give an optimal solution.
Program:
#include<stdio.h> void
main()
{
int i,j,n,m,u;
float value[20],x[20],w[20],p[20],temp,tot;
printf("Enter n"); scanf("%d",&n);
printf("\nEnter elements for weight"); for(i=0;i<n;i++)
{
printf("\n Enter the weight[%d]",i);
scanf("%f",&w[i]);
16
printf("\n Enter the profit[%d]",i);
scanf("%f",&p[i]); value[i]= p[i] /
w[i];
}
printf("\n Enter the maximum weight :");
scanf("%d",&m);
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(value[i]<value[j])
{
temp=w[i];
w[i]=w[j]; w[j]=temp;
temp=p[i]; p[i]=p[j];
p[j]=temp;
temp=value[i];
value[i]=value[j];
value[j]=temp;
}
}
}
printf(" \tWeight \t Profit \t Value");
for(i=0;i<n;i++)
{
printf("\n \t %f \t %f \t %f ",w[i],p[i],value[i]);
}
for(i=0;i<n;i++)
{
x[i]=0.0;
u=m;
}
for(i=0;i<n;i++)
{
if(w[i]<=u)
{
x[i]=1.0; u
= u - w[i]; }
else {
break;
} }
if(i!=n) {
x[i]= u / w[i];
}
tot=0.0;
for(i=0;i<n;i++)
{
tot = tot +( p[i]*x[i] );
17
}
printf("\nOptimum solution is %f",tot);
}
Output
18
Result:
Thus the program to analyze knapsack problem using dynamic programming method is executed and output
is verified successfully.
Ex. No 4 IMPLEMENT THE GRAPH TRAVERSAL TECHNIQUES FOR DEPTH FIRST
SEARCH
Aim:
Implement the DFS algorithm for a graph.
Algorithm:
STEP 1: SET STATUS = 1 (ready state) for each node in G
STEP 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
STEP 3: Repeat Steps 4 and 5 until STACK is empty
STEP 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
STEP 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS = 1) and set
their
STATUS = 2 (waiting state) [END
OF LOOP]
19
STEP 6: EXIT
Program :
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
struct
Vertex {
char label;
bool visited;
};
//stack variables
int stack[MAX];
int top = -1;
//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];
//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;
//stack functions
void push(int item) {
stack[++top] = item;
}
int pop() { return
stack[top--];
}
int peek() {
return stack[top];
}
bool isStackEmpty() {
return top == -1;
}
20
//graph functions
//add vertex to the vertex list void
addVertex(char label) {
struct Vertex* vertex = (struct Vertex*) malloc(sizeof(struct Vertex));
vertex->label = label; vertex->visited = false;
lstVertices[vertexCount++] = vertex;
}
//add edge to edge array void
addEdge(int start,int end) {
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
}
//display the vertex void
displayVertex(int vertexIndex) {
printf("%c ",lstVertices[vertexIndex]->label);
}
//get the adjacent unvisited vertex
int getAdjUnvisitedVertex(int vertexIndex) {
int i;
for(i = 0; i < vertexCount; i++) {
if(adjMatrix[vertexIndex][i] == 1 && lstVertices[i]->visited == false) {
return i;
}
}
return -1;
}
void depthFirstSearch() {
int i;
//mark first node as visited
lstVertices[0]->visited = true;
//display the vertex
displayVertex(0);
//push vertex index in stack
push(0);
while(!isStackEmpty()) {
21
//get the unvisited vertex of vertex which is at top of the stack
int unvisitedVertex = getAdjUnvisitedVertex(peek());
//no adjacent vertex found
if(unvisitedVertex == -1) {
pop();
} else {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
push(unvisitedVertex);
}
}
//stack is empty, search is complete, reset the visited flag
for(i = 0;i < vertexCount;i++) {
lstVertices[i]->visited = false;
}
}
int main() {
int i, j;
for(i = 0; i < MAX; i++) // set adjacency {
for(j = 0; j < MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4
addEdge(0, 1); // S - A
addEdge(0, 2); // S - B addEdge(0,
3); // S - C addEdge(1, 4); // A -
D addEdge(2, 4); // B - D
addEdge(3, 4); // C - D
printf("Depth First Search: ")
depthFirstSearch();
return 0;
}
Output:
22
Depth First Search: S A D B C
Result:
Thus the program to analyze depth first search using graph traversal is executed and output is verified.
Ex. No 5 IMPLEMENT AND ANALYZE BACKTRACKING METHOD FOR SUM OF
SUBSETS PROBLEM.
Aim :
Implement backtracking algorithm for the sum of subsets Problem.
Algorithm:
STEP 1: Start in the leftmost column
STEP 2: If all queens are placed return true
STEP 3: Try all rows in the current column. Do following for every tried row:
23
1. If the queen can be placed safely in this row, then mark this [row, column] as part of the solution and
recursively check if placing queen here leads to a solution.
2. If placing queen in [row, column] leads to a solution then return true
3. If placing queen doesn‟t lead to a solution then unmark this [row, column] (Backtrack)and go to step
(1) to try other rows.
STEP 4: If all rows have been tried and nothing worked, return false to trigger backtracking.
Program:
#include<stdio.h>
int w[20],m,x[20];
void main()
{
int n,r=0,i;
printf("Enter the number of elements");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("w[%d]=",i);
scanf("%d",&w[i]);
}
for(i=1;i<=n;i++)
{
r=r+w[i];
}
printf("\nEnter the constraint");
scanf("%d",&m);
sos(0,1,r);
}
int sos(int s,int k,int r) {
int j;
x[k]=1;
if((s+w[k])==m) {
for(j=1;j<=k;j++)
{
printf("x[%d]=%d\n",j,x[j]);
printf("\n");
}}
else if((s+w[k]+w[k+1])<=m)
{
sos(s+w[k],k+1,r-w[k]);
}
24
if( (s+r-w[k])>=m && (s+w[k+1])<=m )
{ x[k]=0;
sos(s,k+1,r-w[k]);
} return
0; }
Output:
Result:
Thus the program to analyze is sum of subsets problem using backtracking method is executed and output is
verified successfully.
Ex. No 6 IMPLEMENT THE BRANCH AND BOUND TECHNIQUE FOR TRAVELLING
SALESMAN PROBLEM AND COMPARE WITH DYNAMIC PROGRAMMING
Aim:
Implementing branch and bound technique for travelling salesman problem and compare using
dynamic programming.
Algorithm:
STEP 1: Start the process
STEP 2: Accept the number of processes in the ready Queue
STEP 3: For each process in the ready Q, assign the process name and the burst time Step
25
STEP4: Set the waiting of the first process as 0„and its burst time as its turnaround time Step
STEP 5: for each process in the Ready Q calculate
a). Waiting time (n) = waiting time (n-1) + Burst time (n-1) b).
Turnaround time (n) = waiting time(n)+Burst time(n)
STEP 6: Calculate
a) Average waiting time = Total waiting Time / Number of process
b) Average Turnaround time = Total Turnaround Time / Number of process STEP 7: Stop the
process
Program:
#include<stdio.h> void
main()
{
int path[5][5],i,j,min,a[5][5],p,stp,st=1,ed=5,edp,t[5],index;
printf("Enter the cost matrix \n");
for(i=1;i<=5;i++)
{
for(j=1;j<=5;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the number of paths \n");
scanf("%d",&p);
printf("Enter the possible paths:\n");
for(i=1;i<=p;i++) {
for(j=1;j<=5;j++) {
scanf("%d",&path[i][j]);
}
} for(i=1;i<=p;i++)
{ t[i]=0; stp=st;
for(j=1;j<=5;j++) {
edp=path[i][j+1];
t[i]=t[i]+a[stp][edp];
if(edp==ed)
{ break; }
else {
stp=edp;
} } min=t[st];
index=st;
for(i=1;i<=p;i++)
26
{ if(min>t[i]) {
min=t[i];
index=i;
}
}
}
printf("Minimum cost %d",min);
printf("\n Minimum cost path");
for(i=1;i<=5;i++) { printf("->
%d", path[index][i]);
if(path[index][i]==ed) break; }
}
Output:
27
Result:
Thus, the program for branch and bound technique for travelling salesman problem and compare using
dynamic programming has been executed successfully.
28
EX .NO . 7 IMPLEMENT AND ANALYZE THE RANDOMIZED ALGORITHM
FOR HIRING PROBLEM
Aim:
Implement And Analyze The Randomized Algorithm For Hiring Problem
Algorithm :
STEP 1 : Start the Process
STEP 2 : Let n be number of candidate
STEP 3 : best = 0 // Candidate 0 is the least-qualified dummy candidate
STEP 4 : Interview one candidate per day
For i = 1 to n
STEP 5 : Interview candidate i
STEP 6 : If candidate i better than candidate best
STEP 7: best = i
STEP 8 : hire candidate i
STEP 9: Stop the Process
29
SOURCE CODE
#include<stdio.h>
#include<time.h>
#define N 100//Assuming there are 100 applicants
int hireAssistant(int array[],int len);
int main()
{
int count,Array[N];
Array[0]=0;
srand(time(NULL));//Rand needs to set the random seed before calculating the random number, otherwise the
result will be the same every time
for(int i=1;i<N;++i)
{
Array[i]= rand()%N;//Candidates sorted by ability come to interview
randomly printf("Array[i]”); printf(“ ”);
}
Count = hireAssistant(Array,N);
printf(“\n Total number of applicants:" &count)
printf(“\n”)
return 0;
}
int hireAssistant(int array[],int len)
{
int count=0; int
arrayMax=array[0];
printf(“\n"Number of candidate:");
for(int i=1;i<len;++i)
{
if(array[i]>arrayMax)
{
arrayMax=array[i];
printf(“array[i]”);
printf(" ");
count++;
30
}
}
return count;
}
OUTPUT :
First TIme
Second Time
31
RESULT : Thus the program to implement randomized algorithm for hiring problem was executed successfully.
32