0% found this document useful (0 votes)
164 views44 pages

Daa Lab Manual 21cs42

1. The document outlines experiments to be performed in the Design and Analysis of Algorithms Laboratory course. It includes experiments on sorting algorithms like selection sort, quicksort, and merge sort, as well as algorithms for shortest paths, minimum spanning trees, knapsack problems and more. 2. The experiments involve implementing the algorithms in Java, running them on sample input sizes, measuring runtime, and analyzing time complexity. Students will analyze worst case, average case and best case time complexity. 3. Students will plot graphs of runtime versus input size n to compare performance of the different algorithms. They will gain hands-on experience with classic algorithms and analyzing algorithmic efficiency.

Uploaded by

Kaif K
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)
164 views44 pages

Daa Lab Manual 21cs42

1. The document outlines experiments to be performed in the Design and Analysis of Algorithms Laboratory course. It includes experiments on sorting algorithms like selection sort, quicksort, and merge sort, as well as algorithms for shortest paths, minimum spanning trees, knapsack problems and more. 2. The experiments involve implementing the algorithms in Java, running them on sample input sizes, measuring runtime, and analyzing time complexity. Students will analyze worst case, average case and best case time complexity. 3. Students will plot graphs of runtime versus input size n to compare performance of the different algorithms. They will gain hands-on experience with classic algorithms and analyzing algorithmic efficiency.

Uploaded by

Kaif K
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/ 44

DAA LAB MANUAL 21CS42

DESIGN AND ANALYSIS OF


ALGORITHMS LABORATORY
(21CS42)

[As per Choice Based Credit System (CBCS) scheme]


(Effective from the academic year 2021 -2022)

Prepared by : Prof. Syed Zabiulla


Department of Computer Science and Engineering
Experiments
1. Sort a given set of n integer elements using selection sort method and
compute its time complexity. Run the program for varied values of
n>5000 and record the time taken to sort. Plot a graph of the time taken
versus n. The elements can be read from a file or generated using
random number generator. Demonstrate using C++/Java how the brute
force method works along with its time complexity analysis: Worst ,
Average and best case
2. Sort a given set of n integer elements using Quick Sort method and
compute its time complexity. Run the program for varied values of n>
5000 and record the time taken to sort. Plot a graph of the time taken
versus non graph sheet. The elements can be read from a file or can be
generated using the random number generator. Demonstrate using Java
how the divide-and-conquer method works along with its time
complexity analysis: worst case, average case and best case.

3. Sort a given set of n integer elements using Merge Sort method and
compute its time complexity. Run the program for varied values of n>
5000, and record the time taken to sort. Plot a graph of the time taken
versus non graph sheet. The elements can be read from a file or can be
generated using the random number generator. Demonstrate using Java
how the divide-and-conquer method works along with its time
complexity analysis: worst case, average case and best case.

4. Implement in Java, the 0/1 Knapsack problem using


(a) Greedy method.

5. From a given vertex in a weighted connected graph, find shortest


paths to other vertices using Dijkstra's algorithm. Write the program in
Java.

2 DEPT. OF CSE/ISE KNSIT


6. Find Minimum Cost Spanning Tree of a given connected undirected
graph using Kruskal's algorithm. Use Union-Find algorithms in your
program.

7. Find Minimum Cost Spanning Tree of a given connected undirected


graph using Prim's algorithm.

8. Write Java programs to Implement All-Pairs Shortest Paths problem


using Floyd's algorithm.

9. Implement Travelling Sales Person problem using Dynamic


programming.

10. Implement in Java, the 0/1 Knapsack problem using Dynamic


Programming method

11. Design and implement in Java to find a subset of a given set S = {Sl,
S2,.....,Sn} of n positive integers whose SUM is equal to a given
positive integer d. For example, if S ={1, 2, 5, 6, 8} and d= 9, there are
two solutions {1,2,6}and {1,8}. Display a suitable message, if the
given problem instance doesn't have a solution.

12. Design and implement in Java to find all Hamiltonian Cycles in a


connected undirected Graph G of n vertices using backtracking
principle.

3 DEPT. OF CSE/ISE KNSIT


1. Sort a given set of n integer elements using selection
sort method and compute its time complexity. Run
the program for varied values of n>5000 and record
the time taken to sort. Plot a graph of the time
taken versus n. The elements can be read from a file
or generated using random number generator.
Demonstrate using C++/Java how the brute force
method works along with its time complexity
analysis: Worst , Average and best case
import java.util.Random;

import java.util.Scanner;

class SelectionSort

private int a[];

public SelectionSort(int[] a)

this.a = a;

// Selection Sort Method

void sort(int a[])

int n = a.length;

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

int min_element = i;

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

4 Dept. of CSE/ISE ,KNSIT


if (a[j] < a[min_element])

min_element = j;

int temp = a[min_element];

a[min_element] = a[i];

a[i] = temp;

// Method to print the elements of an array

void printarrayay(int a[])

int n = a.length;

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

System.out.print(a[i]+" ");

System.out.println();

}// Main Meth

public class selectionSort

public static void main(String args[])

int n, a[], i;

Scanner input = new Scanner(System.in);

System.out.println("Enter the Size of an Array: ");

n = input.nextInt();

a = new int[n ];

Random rn = new Random();

5 Dept. of CSE/ISE ,KNSIT


System.out.println("System automatically generates numbers ");

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

a[i] = rn.nextInt(n);

SelectionSort ob = new SelectionSort(a);

System.out.println("Before Sort: ");

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

System.out.print(a[i] + "\t");

//int array[] = {15, 10, 99, 53, 36};

ob.sort (a);

System.out.println("Sorted array");

ob.printarrayay(a);

int step = 2000;

double duration;

/* times for n = 0, 10, ..., 100, 200, ..., 5000 */

System.out.println ( "\n\nN\tRepetitions\tTime\n" );

for ( n = 5000; n < 50000; n += step )

a = new int[n+1 ];

SelectionSort ob1 = new SelectionSort(a);

/*get time for size n */

long repetitions = 0;

6 Dept. of CSE/ISE ,KNSIT


long start = System.nanoTime();

do

repetitions++;

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

a[i] = rn.nextInt(n);

a[i] = 100000; //Sentinel value

ob1.sort(a);

} while ( System.nanoTime() - start < 1000000000 );

/* repeat until enough time has elapsed */

duration = ( ( double ) ( System.nanoTime() - start ) ) / 1000000000;

duration /= repetitions;

System.out.println (“\n” +n + "\t" + repetitions + "\t\t" + duration);

// Find it online @ http://tpcg.io/_SXWUP5

7 Dept. of CSE/ISE ,KNSIT


2. Sort a given set of n integer elements using Quick Sort method and compute
its time complexity. Run the program for varied values of n> 5000 and record
the time taken to sort. Plot a graph of the time taken versus non graph sheet.
Īhe elements can be read from a file or can be generated using the random
number generator. Demonstrate using Java how the divide-and-conquer
method works along with its time complexity analysis: worst case, average
case and best case.
import java.util.Random;
import java.util.Scanner;

class QuickSort
{
private int a[];

public QuickSort(int[] a)
{
this.a = a;
}

public int partition ( int a[], int m, int p )


{
int v = a[m];
int i = m;
int j = p;
do
{
while ( a[++ i] < v );
while ( a[-- j] > v );
if ( i < j )
interchange ( a, i, j );
} while ( i <= j );
a[m] = a[j]; a[j] = v;
return j;
}

public void qSort ( int p, int q )


{
int j;

8 Dept. of CSE/ISE ,KNSIT


if ( p < q )
{
j = partition ( a, p, q + 1 );
qSort ( p, j - 1 );
qSort ( j + 1, q );
}
}

public void interchange ( int a[], int i, int j )


{
int t;
t = a[i];
a[i] = a[j];
a[j] = t;
}
}

public class QuickSortDemo


{
public static void main(String[] args)
{
int n, a[], i;
Scanner input = new Scanner(System.in);
System.out.println("Enter the Size of an Array: ");
n = input.nextInt();
a = new int[n + 1];
Random rn = new Random();
System.out.println("System automatically generates numbers ");
for ( i = 0; i < n; ++ i )
{
a[i] = rn.nextInt(n);
}
a[i] = 100000; //Sentinel value
QuickSort qSort = new QuickSort(a);

System.out.println("Before Sort: ");


for ( i = 0; i < n; ++ i )
{
System.out.print(a[i] + "\t");
}

int p = 0;
int q = n - 1;

qSort.qSort(p, q);

9 Dept. of CSE/ISE ,KNSIT


System.out.println("\n\nAfter Sort: ");
for ( i = 0; i < n; ++ i )
{
System.out.print(a[i] + "\t");
}

int step = 2000;


double duration;

/* times for n = 0, 10, ..., 100, 200, ..., 5000 */


System.out.println ( "\n\nN\tRepetitions\tTime\n" );
for ( n = 5000; n < 50000; n += step )
{
a = new int[n + 1];
qSort = new QuickSort(a);

/*get time for size n */


long repetitions = 0;
long start = System.nanoTime();
do
{
repetitions ++;
for ( i = 0; i < n; ++ i )
a[i] = rn.nextInt(n);
a[i] = 100000; //Sentinel value
qSort.qSort(0, n - 1);
} while ( System.nanoTime() - start < 1000000000 );
/* repeat until enough time has elapsed */
duration = ( ( double ) ( System.nanoTime() - start ) ) / 1000000000;
duration /= repetitions;
System.out.println ( n + "\t" + repetitions + "\t\t" + duration );
}
}
}

OUĪPUĪ:
Enter the Size of an Array:
5
System automatically generates numbers
Before Sort:
2 4 0 4 2

After Sort:
0 2 2 4 4

10 Dept. of CSE/ISE ,KNSIT


N Repetitions Time

5000 2604 3.840779374039939E-4


7000 1826 5.47683173603505E-4
9000 1384 7.22663938583815E-4
11000 1116 8.963977114695341E-4
13000 933 0.0010729254876741692
15000 803 0.0012468262278953922
17000 694 0.0014428503530259367
19000 623 0.0016070116115569826
21000 559 0.0017905278372093024
23000 506 0.001978315013833992
25000 465 0.0021531490322580643
27000 428 0.0023395274672897196
29000 396 0.0025256930378787876
31000 369 0.0027141917425474254
33000 345 0.0028995773043478264
35000 325 0.0030829968984615384
37000 305 0.00328287162295082
39000 289 0.003461591204152249
41000 274 0.0036523042846715323
43000 243 0.004119721567901235
45000 248 0.004037317338709678
47000 233 0.004306232450643777
49000 227 0.004423571559471365

11 Dept. of CSE/ISE ,KNSIT


3. Sort a given set of n integer elements using Merge Sort method and compute
its time complexity. Run the program for varied values of n> 5000, and record
the time taken to sort. Plot a graph of the time taken versus non graph sheet.
Īhe elements can be read from a file or can be generated using the random
number generator. Demonstrate using Java how the divide-and-conquer
method works along with its time complexity analysis: worst case, average
case and best case.
import java.util.Random;
import java.util.Scanner;

class MergeSort
{
private int a[];

public MergeSort(int[] a)
{
this.a = a;
}

void merge ( int low, int mid, int high )


{
int b[] = new int[high + 1];
int h = low;
int i = low;
int j = mid + 1;
int k;

while ( ( h <= mid ) && ( j <= high ) )


{
if ( a[h] <= a[j] ) b[i ++] = a[h ++];
else b[i ++] = a[j ++];
}
if ( h > mid )
{
for ( k = j; k <= high; ++ k ) b[i ++] = a[k];
}
else
{

12 Dept. of CSE/ISE ,KNSIT


for ( k = h; k <= mid; ++ k ) b[i ++] = a[k];
}
for ( k = low; k <= high; ++ k ) a[k] = b[k];
}

void mergeSort ( int low, int high )


{
int mid;

if ( low < high )


{
mid = ( low + high ) / 2;

mergeSort ( low, mid );


mergeSort ( mid + 1, high );

merge ( low, mid, high );


}
}
}

public class MergeSortDemo


{
public static void main(String[] args)
{
int n, a[], i;
Scanner input = new Scanner(System.in);
System.out.println("Enter the Size of an Array: ");

n = input.nextInt();
a = new int[n + 1];

Random rn = new Random();


System.out.println("System automatically generates numbers ");
for ( i = 0; i < n; ++ i )
{
a[i] = rn.nextInt(n);//a[i] = input.nextInt();
}
a[i] = 100000; //Sentinel value
MergeSort mSort = new MergeSort(a);

System.out.println("Before Sort: ");


for ( i = 0; i < n; ++ i )
{
System.out.print(a[i] + "\t");
}

13 Dept. of CSE/ISE ,KNSIT


int low = 0;
int high = n - 1;

mSort.mergeSort(low, high);

System.out.println("\n\nAfter Sort: ");


for ( i = 0; i < n; ++ i )
{
System.out.print(a[i] + "\t");
}

int step = 2000;


double duration;

/* times for n = 0, 10, ..., 100, 200, ..., 5000 */


System.out.println ( "\n\nN\tRepetitions\tTime\n" );
for ( n = 5000; n < 50000; n += step )
{
a = new int[n + 1];
mSort = new MergeSort(a);

/*get time for size n */


long repetitions = 0;
long start = System.nanoTime();
do
{
repetitions ++;
for ( i = 0; i < n; ++ i )
a[i] = rn.nextInt(n);
a[i] = 100000; //Sentinel value
mSort.mergeSort(0, n - 1);
} while ( System.nanoTime() - start < 1000000000 );
/* repeat until enough time has elapsed */
duration = ( ( double ) ( System.nanoTime() - start ) ) / 1000000000;
duration /= repetitions;
System.out.println ( n + "\t" + repetitions + "\t\t" + duration );

}
}
}

OUTPUT:
Enter the Size of an Array:
5
System automatically generates numbers

14 Dept. of CSE/ISE ,KNSIT


Before Sort:
4 2 1 2 3

After Sort:
1 2 2 3 4

N Repetitions Time

5000 199 0.005027964120603015


7000 153 0.0065458487124183005
9000 97 0.010360987432989691
11000 59 0.017194349559322034
13000 54 0.018756191537037035
15000 42 0.024344312833333333
17000 33 0.030582966272727274
19000 27 0.03758708807407407
21000 22 0.046705298409090906
23000 18 0.05575357561111111
25000 16 0.0653416245625
27000 13 0.07881347792307693
29000 10 0.1020311572
31000 11 0.09932865818181819
33000 10 0.110072756
35000 9 0.12348744877777779
37000 8 0.139554033875
39000 7 0.15578334585714287
41000 7 0.16581026885714284
43000 6 0.19381527966666667
45000 5 0.215364133
47000 5 0.22233623480000003
49000 4 0.25112471825

15 Dept. of CSE/ISE ,KNSIT


4. Implement in Java, the 0/1 Knapsack problem using
(a) Dynamic Programming method

import java.util.Scanner;
class DKnapsack
{
int n;
int c;
int p[];
int w[];
int v[][];

public DKnapsack(int n, int c, int[] p, int[] w)


{
super();
this.n = n;
this.c = c;
this.p = p;
this.w = w;
this.v = new int[n + 1][c + 1];
}

void compute()
{
for ( int i = 0; i <= n; ++ i)
{
for ( int j = 0; j <= c; ++ j)
{
if ( i == 0 || j == 0 )
{
v[i][j] = 0;
}
else if ( j - w[i] >= 0 )
{
v[i][j] = max ( v[i - 1][j], p[i] + v[i - 1][j - w[i]]);
}
else if ( j - w[i] < 0 )
{
v[i][j] = v[i - 1][j];
}
}
}

16 Dept. of CSE/ISE ,KNSIT


System.out.println("Optimal Solution: " + v[n][c]);
traceback();
}

void traceback()
{
System.out.println("The objects picked up into knapsack are:");

int i = n;
int j = c;

while( i > 0)
{
if(v[i][j] != v[i-1][j])
{
System.out.print(i + " ");
j = j - w[i];
i--;
}
else
{
i--;
}
}
}

private int max(int i, int j)


{
if ( i > j ) return i;
else return j;
}
}
public class KpDynamic
{
public static void main(String[] args)
{
int n;
int c;

Scanner input = new Scanner(System.in);


System.out.println("Enter number of objects");
n = input.nextInt();

int[] p = new int[n+1];


int[] w = new int[n+1];
int i;

17 Dept. of CSE/ISE ,KNSIT


System.out.println("Enter capacity of Knapsack");
c = input.nextInt();

System.out.println("Enter profit for each " + n + " objects");

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


p[i] = input.nextInt();

System.out.println("Enter weight for each " + n + " objects");

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


w[i] = input.nextInt();

DKnapsack dk = new DKnapsack(n, c, p, w);


dk.compute();
}
}

OUĪPUĪ:
Enter number of objects
5
Enter capacity of Knapsack
20
Enter profit for each 5 objects
3
4
5
8
10
Enter weight for each 5 objects
2
3
4
5
9
Optimal Solution: 26
The objects picked up into knapsack are:
5431

18 Dept. of CSE/ISE ,KNSIT


(b) Greedy method.
import java.util.Scanner;

class GKnapsack
{
int n;
double c;
double p[];
double w[];

public GKnapsack(int n, double c, double[] p, double[] w)


{
super();
this.n = n;
this.c = c;
this.p = p;
this.w = w;
}

void compute()
{
int i;
double[] x= new double[n+1];

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


{
x[i] = 0.0;
}

double rc = c;

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


{
if(w[i] > rc) break;
x[i] = 1;
rc = rc - w[i];
}

if(i<=n)
{
x[i] = rc/w[i];
}

double netProfit = 0.0;

19 Dept. of CSE/ISE ,KNSIT


for ( i = 0; i < n; ++ i)
{
if ( x[i] > 0.0)
{
netProfit = netProfit + x[i] * p[i];

System.out.println("Net Profit: " + netProfit);


System.out.println("The objects picked up into knapsack are:");

for ( i = 0; i < n; ++ i)
{
System.out.println(x[i] + " ");

}
}
}

public class KpGreedy


{
public static void main(String[] args)
{
int n;
double c;

Scanner input = new Scanner(System.in);


System.out.println("Enter number of objects");
n = input.nextInt();

double[] p = new double[n+1];


double[] w = new double[n+1];
int i;

System.out.println("Enter capacity of Knapsack");


c = input.nextDouble();

System.out.println("Enter profit for each " + n + " objects");

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


p[i] = input.nextDouble();

System.out.println("Enter weight for each " + n + " objects");

20 Dept. of CSE/ISE ,KNSIT


for ( i = 0; i < n; i ++)
w[i] = input.nextDouble();

GKnapsack gk = new GKnapsack(n, c, p, w);


gk.compute();
}
}

OUĪPUĪ:
Enter number of objects
7
Enter capacity of Knapsack
15
Enter profit for each 7 objects
6
10
18
15
3
5
7
Enter weight for each 7 objects
1
2
4
5
1
3
7
Net Profit: 55.333333333333336
The objects picked up into knapsack are:
1.0
1.0
1.0
1.0
1.0
0.6666666666666666
0.0

21 Dept. of CSE/ISE ,KNSIT


5. From a given vertex in a weighted connected graph, find shortest paths
to other vertices using Dijkstra's algorithm. Write the program in Java.
import java.util.Arrays;
import java.util.Scanner;

public class Dijkstra


{

static int n,cost[][],i,j,u,dist[],src;


void dij(int src,int cost[][],int dist[],int n)
{
int visited[],min;
visited=new int[n];

for(i=0;i<n;i++)
{
visited[i]=0;
dist[i]=cost[src][i];
}

visited[src]=1;
dist[src]=0;

for(i=0;i<n;i++)
{
if(i==src) continue;
min=999;

for(j=0;j<n;j++)
if((visited[j]==0)&&(min>dist[j]))
{
min=dist[j];
u=j;
}
visited[u]=1;

for(j=0;j<n;j++)
if(visited[j]==0)
{
if(dist[j]>dist[u]+cost[u][j])
dist[j]=dist[u]+cost[u][j];
}
}
}

22 Dept. of CSE/ISE ,KNSIT


public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of vertices");
n=sc.nextInt();

System.out.println("Enter the matrix");


cost=new int[n][n];
dist=new int[n];

Arrays.fill(dist,0);

for(i=0;i<n;i++)
for(j=0;j<n;j++)
cost[i][j]=sc.nextInt();

System.out.println("Enter the source vertex");


src=sc.nextInt();

new Dijkstra().dij(src, cost, dist, n);

System.out.println("Shortest path from "+src+" to all other vertices");


for(i=0;i<n;i++)
System.out.println("To " +i+" is "+dist[i]);
}
}

OUĪPUĪ:
Enter the number of vertices
4
Enter the matrix
0 15 10 9999
9999 0 15 9999
20 9999 0 20
9999 10 9999 0
Enter the source vertex
2
Shortest path from 2 to all other vertices
To 0 is 20
To 1 is 30
To 2 is 0
To 3 is 20

23 Dept. of CSE/ISE ,KNSIT


6. Find Minimum Cost Spanning Īree of a given connected undirected graph using
Kruskal's algorithm. Use Union-Find algorithms in your program.
import java.util.Scanner;

public class Kruskals


{
static int parent[],cost[][], mincost,n,i,j,ne,a,b,min,u,v;

public void kruskal(int n,int[][] cost)


{
ne=1;
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
if(cost[i][j]<min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}

u=find(u);
v=find(v);

if(v!=u)
{
System.out.println( ne+"edge("+a+","+b+")="+min);
ne=ne+1;
mincost=mincost+min;
uni(u,v);
}
cost[a][b]=cost[b][a]=999;
}
System.out.println("The minimum cost of spanning tree is "+mincost);
}

public int find (int i)


{

24 Dept. of CSE/ISE ,KNSIT


while (parent[i] != 0)
i=parent[i];
return i;
}

public void uni(int i,int j)


{
parent[j]=i;
}

public static void main(String[] args)


{

Scanner sc=new Scanner(System.in);

System.out.println("Enter the number of vertices\n");


n=sc.nextInt();

int cost[][]= new int [n+1][n+1];

parent=new int[n+1];

System.out.println("Enter the cost matrix\n");


for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j]=sc.nextInt();
if(cost[i][j]==0)
cost[i][j]=999;
}
}

Kruskals k = new Kruskals();


k.kruskal(n,cost);

OUĪPUĪ:
Enter the number of vertices

25 Dept. of CSE/ISE ,KNSIT


7
Enter the cost matrix

0 28 999 999 999 10 999

28 0 16 999 999 999 14

999 16 0 12 999 999 999

999 999 12 0 22 999 18

999 999 999 22 0 25 24

10 999 999 999 25 999 999

999 14 999 18 24 999 999

1edge(1,6)=10
2edge(6,5)=25
3edge(5,4)=22
4edge(4,3)=12
5edge(3,2)=16
6edge(2,7)=14

The minimum cost of spanning tree is 99

26 Dept. of CSE/ISE ,KNSIT


27 Dept. of CSE/ISE ,KNSIT
7. Find Minimum Cost Spanning Īree of a given connected undirected graph using
Prim's algorithm.
import java.util.Scanner;

public class Prims


{
static int mincost=0,n,i,j,ne,a=0,b=0,min,u = 0,v=0;

public void prim(int n,int[][] cost)


{

int[] visited = new int[n+1];

for(i=2;i<=n;i++)
visited[i]=0;

visited[1]=1;
ne=1;
while(ne<n)
{
min=999;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<min)
{
if(visited[i]==0)
continue;
else
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
}
if(visited[u]==0||visited[v]==0)
{

System.out.println((ne)+"edge("+a+","+b+")="+min);
ne=ne+1;

28 Dept. of CSE/ISE ,KNSIT


mincost=mincost+min;
visited[v]=1;

}
cost[a][b]=cost[b][a]=999;
}
System.out.println("The minimum cost of spanning tree is "+mincost);

public static void main(String[] args)


{
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of vertices\n");


n=sc.nextInt();

int cost[][]= new int [n+1][n+1];


System.out.println("Enter the cost matrix\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j]=sc.nextInt();
if(cost[i][j]==0)
cost[i][j]=999;
}
}

Prims p = new Prims();


p.prim(n,cost);
}

OUĪPUĪ:
Enter the number of vertices
7
Enter the cost matrix

0 28 999 999 999 10 999

28 0 16 999 999 999 14

29 Dept. of CSE/ISE ,KNSIT


999 16 0 12 999 999 999

999 999 12 0 22 999 18

999 999 999 22 0 25 24

10 999 999 999 25 999 999

999 14 999 18 24 999 999

1edge(1,6)=10
2edge(6,5)=25
3edge(5,4)=22
4edge(4,3)=12
5edge(3,2)=16
6edge(2,7)=14

The minimum cost of spanning tree is 99

30 Dept. of CSE/ISE ,KNSIT


31 Dept. of CSE/ISE ,KNSIT
8. Write Java programs to (a) Implement All-Pairs Shortest Paths problem
usingFloyd's algorithm.
import java.util.*;

public class Floyds


{
static int n,i,j,k;

public void floyd(int n , int[][] cost)


{

for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j]);

}
}
}

System.out.println("all pair shortest paths matrix \n");

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
System.out.print(cost[i][j]+" ");
}
System.out.println();
}

public int min(int i,int j)


{
if(i<j)
return i;
else
return j;

32 Dept. of CSE/ISE ,KNSIT


}

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);

System.out.println("Eneter the no of vertices\n");


n=sc.nextInt();

int cost[][]=new int[n+1][n+1];


System.out.println("Enter the cost matrix:");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j]=sc.nextInt();

Floyds f = new Floyds();


f.floyd(n,cost);

OUĪPUĪ:
Enter the number of vertices
5

Enter the cost matrix:


0 5 999 2 999
999 0 2 999 999
3 999 0 999 7
999 999 4 0 1
1 3 999 999 0
all pair shortest paths matrix

05623
50278
38056
24401
13530

33 Dept. of CSE/ISE ,KNSIT


34 Dept. of CSE/ISE ,KNSIT
(b) Implement Īravelling Sales Person problem using Dynamic programming.

import java.util.Scanner;

public class Tsp


{
static int cost[][];

public int tsp(int[] path,int start,int n)


{
int i,j,k,ccost;

int[] mintour=new int[n+1];


int[] temp=new int[n+1];

if(start==n-1)
return cost[path[n-1]][path[n]]+cost[path[n]][1];

int mincost=999;

for(i=start+1;i<=n;i++)
{
for(j=1;j<=n;j++)
temp[j]=path[j];

temp[start+1]=path[i];
temp[i]=path[start+1];

if(cost[path[start]][path[i]]+(ccost=tsp(temp,start+1,n))<mincost)
{
mincost=cost[path[start]][path[i]]+ccost;

for(k=1;k<=n;k++)
mintour[k]=temp[k];

}
}

for(i=1;i<=n;i++)
path[i]=mintour[i];

return mincost;

35 Dept. of CSE/ISE ,KNSIT


}

public static void main(String[] args)


{
int mincost,n,i,j;
Scanner s = new Scanner(System.in);

System.out.println("enter the no of cities");


n=s.nextInt();

int path[] =new int[n+1];


cost = new int[n+1][n+1];

System.out.println("Enter the cost matrix");


for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j]=s.nextInt();
for(i=1;i<=n;i++)
path[i]=i;

Tsp obj = new Tsp();

mincost=obj.tsp(path,1,n);

System.out.println("tsp tour");
for(i=1;i<=n;i++)
System.out.print(path[i] + "--->");

System.out.println("1");
System.out.println("Tourcost=" + mincost);
}

OUĪPUĪ:

Enter the no of cities


4

36 Dept. of CSE/ISE ,KNSIT


Enter the cost matrix

999 1 3 6
1 999 2 3
3 2 999 1
6 3 1 999

tsp tour
1--->2--->4--->3--->1
Tourcost = 8

37 Dept. of CSE/ISE ,KNSIT


9. Design and implement in Java to find a subset of a given set S = {Sl, S2, ...... ,Sn}
of n positive integers whose SUM is equal to a given positive integer d. For
example, if S ={1, 2, 5, 6, 8} and d= 9, there are two solutions {1,2,6}and
{1,8}. Display a suitable message, if the given problem instance doesn't have a
solution.
import java.util.Scanner;
public class Subset
{
static int w[],x[],flag,sum,n,total,i,s,k,r;
public void sumOfSubset(int s,int k,int r)
{
x[k]=1;
if(s+w[k]==sum)
{
System.out.println("The subset: ");
for(i=1;i<=k;i++)
{
flag=1;
if(x[i]==1)
{
System.out.println(w[i]);
}
}
}

else if(s+w[k]+w[k+1]<=sum)
{
sumOfSubset(s+w[k],k+1,r-w[k]);
}
if(s+r-w[k]>=sum && s+w[k+1]<=sum)
{
x[k]=0;
sumOfSubset(s,k+1,r-w[k]);
}
}
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the number of elements");
n=s.nextInt();
w=new int[n+1];

38 Dept. of CSE/ISE ,KNSIT


x=new int[n+1];
System.out.println("Enter the elements");
for(int i=1;i<=n;i++)
{
w[i]=s.nextInt();
total=total+w[i];
}
System.out.println("Enter the sum");
sum=s.nextInt();
if(total<sum)
{
System.out.println("subset is not possible");
System.exit(0);
}
Subset ss = new Subset();
ss.sumOfSubset(0,1,total);
if(flag==0)
{
System.out.println("Subset not possible");
}
}
}

OUĪPUĪ:

Enter the number of elements

Enter the elements

1 2 3 4 5 6 7

Enter the sum

The subset:

39 Dept. of CSE/ISE ,KNSIT


5

The subset:

The subset:

The subset:

The subset:

40 Dept. of CSE/ISE ,KNSIT


10. Design and implement in Java to find all Hamiltonian Cycles in a connected
undirected Graph G of n vertices using backtracking principle.

import java.util.Scanner;

class HamiltonianCycles
{
int n,g[][],x[],i,j,k;

public HamiltonianCycles(int n,int[][] g)


{
this.n=n;
this.g=g;
this.x = new int[n+1];
x[1]=1;

public void hamiltonian(int k)


{

while(true)
{
nextValue(k);

if(x[k] == 0)
{
return;

if(k==n)
{
System.out.println("Solution :");
for(int i=1;i<=n;i++)
{
System.out.print(x[i] + "\t");

System.out.println(1);
}

41 Dept. of CSE/ISE ,KNSIT


else
{
hamiltonian(k+1);
}

}
}

public void nextValue(int k)


{

while(true)
{
x[k] = (x[k]+1)%(n+1);

if(x[k]==0)
{
return;
}

if(g[x[k-1]][x[k]] != 0)
{
for(j=1;j<=k-1;j++)
{
if(x[j] == x[k])
{
break;
}
}

if(j==k)
{
if((k<n) || ((k==n) && (g[x[n]][x[1]] != 0 )))
{
return;
}
}

}
}

42 Dept. of CSE/ISE ,KNSIT


public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);

System.out.println("Enter the number of vertices :");


n=s.nextInt();

int[][] g = new int[n+1][n+1];


System.out.println("Enter the matrix :");
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
g[i][j]=s.nextInt();

HamiltonianCycles ham = new HamiltonianCycles(n,g);

ham.hamiltonian(2);

}
}

OUĪPUĪ:

Enter the number of vertices :


4
Enter the matrix :
0 4 1 3
4 0 2 1
1 2 0 5
3 1 5 0
Solution :
1 2 3 4 1
Solution :
1 2 4 3 1
Solution :
1 3 2 4 1
Solution :
1 3 4 2 1
Solution :
1 4 2 3 1
Solution :
1 4 3 2 1

43 Dept. of CSE/ISE ,KNSIT


44 Dept. of CSE/ISE ,KNSIT

You might also like