Daa Lab Manual Cse III I Sem
Daa Lab Manual Cse III I Sem
Daa Lab Manual Cse III I Sem
List of Experiments
1. Write a java program to implement Quick sort algorithm for sorting a list of integers
in ascending order
2. Write a java program to implement Merge sort algorithm for sorting a list of integers
in ascending order.
i) Write a java program to implement the DFS algorithm for a graph.
ii) Write a. java program to implement the BFA algorithm for a graph.
3. Write a java programs to implement backtracking algorithm for the N-queens
problem.
4. Write a java program to implement the backtracking algorithm for the sum of subsets
problem.
5. Write a java program to implement the backtracking algorithm for the Hamiltonian
Circuits problem.
6. Write a java program to implement greedy algorithm for job sequencing with
deadlines.
7. Write a java program to implement Dijkstra’s algorithm for the Single source shortest
path problem.
8. Write a java program that implements Prim’s algorithm to generate minimum cost
spanning tree.
9. Write a java program that implements Kruskal’s algorithm to generate minimum cost
spanning tree
10. Write a java program to implement Floyd’s algorithm for the all pairs shortest path
problem.
11. Write a java program to implement Dynamic Programming algorithm for the 0/1
Knapsack problem.
12. Write a java program to implement Dynamic Programming algorithm for the Optimal
Binary Search Tree Problem.
PROGRAM-1
1. Write a java program to implement Quick sort algorithm for sorting a list of integers
in ascending order
}
//This method sorts the input array in ascecnding order using quick sort
static void quickSortInAscendingOrder (int[] numbers, int low, int high)
{
inti=low;
int j=high;
int temp;
int middle=numbers[(low+high)/2];
while (i<j)
{
while (numbers[i]<middle)
{
i++;
}
while (numbers[j]>middle)
{
j--;
}
if (i<=j)
{
temp=numbers[i];
numbers[i]=numbers[j];
numbers[j]=temp;
i++;
j--;
}
}
if (low<j)
{
quickSortInAscendingOrder(numbers, low, j);
}
if (i<high)
{
quickSortInAscendingOrder(numbers, i, high);
}
}
}
Output:
2. Write a java program to implement Merge sort algorithm for sorting a list of integers
in ascending order.
if (lowerIndex<higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
}
}
Output:
4 11 23 28 43 45 65 77 89 98
i) Write a java program to implement the dfs algorithm for a graph.
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
Node(int data)
{
this.data=data;
this.neighbours=new ArrayList<>();
}
public void addneighbours(Node neighbourNode)
{
this.neighbours.add(neighbourNode);
}
public List<Node>getNeighbours() {
return neighbours;
}
public void setNeighbours(List<Node>neighbours) {
this.neighbours = neighbours;
}
}
// Recursive DFS
public voiddfs(Node node)
{
System.out.print(node.data + " ");
List<Node>neighbours=node.getNeighbours();
node.visited=true;
for (inti = 0; i<neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited){
dfs(n);
}
}
}
// Iterative DFS using stack
public voiddfsUsingStack(Node node)
{
Stack<Node> stack=new Stack<Node>();
stack.add(node);
node.visited=true;
while (!stack.isEmpty())
{
Node element=stack.pop();
System.out.print(element.data + " ");
List<Node>neighbours=element.getNeighbours();
for (inti = 0; i<neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
stack.add(n);
n.visited=true;
}
}
}
}
node40.addneighbours(node10);
node40.addneighbours(node20);
node10.addneighbours(node30);
node20.addneighbours(node10);
node20.addneighbours(node30);
node20.addneighbours(node60);
node20.addneighbours(node50);
node30.addneighbours(node60);
node60.addneighbours(node70);
node50.addneighbours(node70);
DepthFirstSearchExampleNeighbourListdfsExample = new
DepthFirstSearchExampleNeighbourList();
System.out.println("The DFS traversal of the graph using stack ");
dfsExample.dfsUsingStack(node40);
System.out.println();
// Resetting the visited flag for nodes
node40.visited=false;
node10.visited=false;
node20.visited=false;
node30.visited=false;
node60.visited=false;
node50.visited=false;
node70.visited=false;
Output:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
Node(int data)
{
this.data=data;
this.neighbours=new ArrayList<>();
}
public void addneighbours(Node neighbourNode)
{
this.neighbours.add(neighbourNode);
}
public List<Node>getNeighbours() {
return neighbours;
}
public void setNeighbours(List<Node>neighbours) {
this.neighbours = neighbours;
}
}
public BreadthFirstSearchExampleNeighbourList()
{
queue = new LinkedList<Node>();
}
public void bfs(Node node)
{
queue.add(node);
node.visited=true;
while (!queue.isEmpty())
{
Node element=queue.remove();
System.out.print(element.data + "\t");
List<Node>neighbours=element.getNeighbours();
for (inti = 0; i<neighbours.size(); i++) {
Node n=neighbours.get(i);
if(n!=null && !n.visited)
{
queue.add(n);
n.visited=true;
}
}
}
}
}
}
OUTPUT:
//If Grid is 1*1 or 2*2 or 3*3 then solution is not possible as,
//In 1*1 or 2*2 grid, Queen placed in 1st row at any position will attack queen placed at all the
positions in row 2.
//In 3*3 grid, Queen placed in 1st row and 2nd row for all combinations position will attack
queen placed at all the positions in row 3.
if(gridSize<4){
System.out.println("No Solution available");
}else{
int[][] board = new int[gridSize][gridSize];
placeAllQueens(board, 0);
printBoard(board);
}
}
private static booleanplaceAllQueens(int board[][], int row)
{
if(row>=board.length){
return true;
}
booleanisAllQueensPlaced = false;
for (int j = 0; j <board.length; j++)
{
if(isSafe(board, row, j)){
board[row][j] = 1;
isAllQueensPlaced = placeAllQueens(board, row+1);
}
if(isAllQueensPlaced)
{
break;
}
else
{
board[row][j] = 0;
}
}
return isAllQueensPlaced;
}
return true;
}
}
Output:
_Q__
___Q
Q___
__Q_
PROGRAM-4
4. Write a java program to implement the backtracking algorithm for the sum of subsets
problem.
import java.util.Scanner;
public class Subset
{
static int c=0;
public static void main(String[] args)
{
int w[]=new int[10];
int n, d, i, sum=0;
int x[]=new int[10];
Scannerin=new Scanner(System.in);
System.out.println("********** SUBSET PROBLEM ************");
System.out.println("Enter the number of elements: ");
n=in.nextInt();
System.out.println("Enter the elements in increasing order");
for(i=0;i<n;i++)
w[i]=in.nextInt();
System.out.println("Enter the value of d: ");
d=in.nextInt();
for(i=0;i<n;i++)
sum=sum+w[i];
System.out.println("SUM ="+sum);
if(sum < d || w[0] > d){
System.out.println("Subset is not possible ! ");
System.exit(0);
}
subset(0,0,sum,x,w,d);
if(c==0)
System.out.println("Subset is not possible ! ");
System.out.println("\n********** ********* *************");
}
static void subset(int cs, int k, int r,int x[],int w[],int d)
{
x[k] = 1;
if(cs+w[k] == d)
{
c++;
System.out.print("\nSolution "+c+" is {");
for(int i=0;i<=k;i++)
if(x[i] == 1)
{
System.out.print(w[i]+" ");
}
System.out.print("}");
}
else if((cs + w[k] + w[k+1]) <= d)
subset(cs + w[k], k+1, r-w[k],x,w,d);
if((cs + r -w[k]) >=d && (cs + w[k+1]) <= d)
{
x[k] = 0;
subset(cs, k+1, r-w[k],x,w,d);
}
}
}
Output:
********** SUBSET PROBLEM ************
Enter the number of elements:5
Hamiltonian (2,G,x,n);
if (found == false)
System.out.println(“No Solution possible!”);
}
static void Hamiltonian(int k,int G[][],int x[],int n)
{
while(true)
{
NextValue(k,G,x,n);
if(x[k] == 0)
return;if(k == n)
{
for(int i=1; i<=k;i++)
System.out.print(x[i]+” “);
System.out.println();
found= true;
return;
}
else
Hamiltonian(k+1,G,x,n);
}
}
static void NextValue(int k,int G[][],int x[],int n)
{
while(true)
{
x[k] = (x[k]+1)%(n+1);
if(x[k] == 0)
return;
if(G[x[k-1]][x[k]] !=0)
{
int j;
for(j = 1; j<k; j++)
if(x[k] == x[j])
break;
if(j==k)
if( (k<n) || ( (k==n) && G[x[n]][x[1]] != 0 ) )
return;
}
}
}
}
OUTPUT
Hamiltonian Cycle
Solution 2 is {1 8 }
Solution 3 is {3 6 }
PROGRAM-6
6. Write a java program to implement greedy algorithm for job sequencing with deadlines.
import java.util.*;
class job
{
int p; // ............. for profit of a job
int d; // ............. for deadline of a job
int v; // ............ for checking if that job has been selected
job()
{
p=0;
d=0;
v=0;
}
job(int x,int y,int z) // parameterised constructor
{
p=x;
d=y;
v=z;
}
}
class js
{
static int n;
static int out(job jb[],int x)
{
for(int i=0;i<n;++i)if(job[i].p==x)
return i;
return 0;
}
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
System.out.println("Enter the number of jobs");
n=scr.nextInt();
int max=0; // this is to find the maximum deadline
job jb[]=new job[n];
for(int i=0;i<n;++i)
{
System.out.println("Enter profit and deadline(p d)");
int p=scr.nextInt();int d=scr.nextInt();if(max<d)
max=d; // assign maximum value of deadline to "max" variable
jb[i]=new job(p,d,0); //zero as third parameter to mark that initially it is unvisited
}
//accepted jobs from user
for(int i=0;i<=n-2;++i)
{
for(int j=i;j<=n-1;++j)
{
if(jb[i].d>jb[j].d)
{
job temp=jb[i];
jb[i]=jb[j];
jb[j]=temp;
}
}
}
// sorting process ends
System.out.println("The jobs are as follows ");
for(int i=0;i<n;++i)
System.out.println("Job "+i+" Profit = "+jb[i].p+" Deadline = "+jb[i].d);
// jobs displayed to the user
int count;
int hold[]=new int[max];
for(int i=0;i<max;++i)
hold[i]=0;
for(int i=0;i<n;++i)
{
count=0;
for(int j=0;j<n;++j)
{
if(count<jb[j].d && jb[j].v==0 && count<max && jb[j].p>hold[count])
{
int ch=0;
if(hold[count]!=0)
{
ch=out(jb,hold[count]);
jb[ch].v=0;
}
hold[count]=jb[j].p;
jb[j].v=1;
++count;
}
}
}
int profit=0;
for(int
i=0;i<max;++i)
profit+=hold[i];
System.out.println("The maximum profit is "+profit);
}
}
OUTPUT
7. Write a java program to implement Dijkstra’s algorithm for the Single source
shortest path problem.
import java.util.Scanner;
int i, j;
int n= in.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cost[i][j] = in.nextInt();
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
System.out.print(cost[i][j]+"\t");
}
System.out.println();
}
System.out.println("Enter the source vertex: ");
int sv = in.nextInt();
dij(cost,dist,sv,n,path,visited);
printpath(sv,n,dist,path,visited );
visited[i]=0;
dist[i] = cost[sv][i];
if(cost[sv][i] == 999)
path[i] = 0;
else
path[i] = sv;
visited[sv]=1;
while(count<=n)
min = 999;
v = w;
}
visited[v] = 1;
count++;
path[w] = v;
while(t != sv)
{
System.out.print("<-->"+t);
t=path[t];
}
System.out.print("<-->"+sv);
OUTPUT
0 5 0 999
5 0 1 999
999 1 999 2
999 999 5 0
0 5 0 999
5 0 1 999
999 1 999 2
999 999 5 0
1-> =2 is :1
2<-→3<-→1
import java.util.Scanner;
int i, j, mincost = 0;
int n = in.nextInt();
cost[i][j] = in.nextInt();
{System.out.print(cost[i][j]+"\t");
}
System.out.println();
mincost=prims(cost,n,mincost);
System.out.print(+mincost);
nearV[i]=1;
nearV[1]=0;
int min=999;
for(j=1;j<=n;j++)
min=cost[j][nearV[j]];
u=j;
}
}
t[i][1] = u;
t[i][2] = nearV[u];
mincost += min;
nearV[u] = 0;
nearV[k] = u;
return mincost;
Output:
3
Enter the cost matrix
999
0
1
999
0
The entered cost matrix is
0 2 999
2 0 1
999 1 0
parent[v] =u;
}
cost[a][b] = cost[b][a] = 999;
}
return mincost;
}
}
Output:
********* KRUSKAL'S ALGORITHM
*******Enter the number of nodes:
3
Enter the cost matrix
0
2
6
2
0
2
6
2
0
The entered cost matrix is
0 2 6
2 0 2
6 2 0
1>minimum edge is :(1,2) and its cost
is:22>minimum edge is :(2,3) and its cost
is: 2
PROGRAM-10
10. Write a java program to implement Floyd’s algorithm for the all pairs
shortest path problem
import java.util.Scanner;
class Floyd {
int i, j;
System.out.println("***********FLOYD'SALGORITHM**********");
int n = in.nextInt();
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
a[i][j] = in.nextInt();
for(i=1;i<=n;i++)
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
floyd(a,n);
System.out.print(a[i][j]+"\t");
System.out.println();
if(a>b)
return b;
else
return a;
}
Output:
***********FLOYD'SALGORITHM**********
999
999
33
3
Entered adjacency matrix is:
0 1 3 1
2 0 5 999
4 7 999 1
33 2 1 3
0 1 2 1
2 0 4 3
4 3 2 1
4 2 1 2
PROGRAM-11
11. Write a java program to implement Dynamic Programming algorithm for the 0/1
Knapsack problem.
import java.util.Scanner;
public class Knapsack6a
{
static final int MAX = 20; // max. no. of
objectsstatic int w[]; // weights 0 to n-1
static int p[]; // profits 0 to n-1
static int n;
// no. of objects
static int M;
// capacity of Knapsack
static int V[][];
// DP solution process -table
static int Keep[][]; // to get objects in optimal solution
public static void main(String args[])
{
w = new
int[MAX];p = new
int[MAX];
V = new int [MAX][MAX];
Keep = new
int[MAX][MAX];int
optsoln;
ReadObjects();
for (int i = 0; i <= M;
i++)V[0][i] = 0;
for (int i = 0; i <= n;
i++)V[i][0] = 0;
optsoln = Knapsack();
System.out.println("Optimal solution = " + optsoln);
}
static int Knapsack()
{
int r; // remaining Knapsack capacity
for (int i = 1; i <= n; i++)
for (int j = 0; j <= M; j++)
if ((w[i] <= j) && (p[i] + V[i -1][j -w[i]] > V[i -1][j]))
{
V[i][j] = p[i] + V[i -1][j -w[i]];
Keep[i][j] = 1;
}
else
{
V[i][j] = V[i -1][j];
Keep[i][j] = 0;
}
// Find the objects included in the Knapsack
r = M;
System.out.println("Items = ");
for (int i = n; i > 0; i--) // start from
Keep[n,M]if (Keep[i][r] == 1)
{
System.out.println(i + "
");r = r -w[i];
}
System.out.println();
return V[n][M];
}
static void ReadObjects()
{
Scanner scanner = new Scanner(System.in);
System.out.println("Knapsack Problem -Dynamic Programming Solution: ");
System.out.println("Enter the max capacity of knapsack: ");
M = scanner.nextInt();
System.out.println("Enter number of objects: ");
n = scanner.nextInt();
System.out.println("Enter Weights: ");
for (int i = 1; i <= n; i++)
w[i] = scanner.nextInt();
System.out.println("Enter Profits: ");
for (int i = 1; i <= n; i++)
p[i] = scanner.nextInt();
scanner.close();
}
}
Output:
6)b. Implement in Java, the 0/1 Knapsack problem using Greedy method.
import java.util.Scanner;
import java.util.Scanner;
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-
1][w]);else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
Output:
PROGRAM-12
import java.io.*;
import
java.util.*;class
Optimal
{
public int p[];
public int q[];
public int a[];
public int
w[][];
public int c[][];
public int r[][];
public int n;
int front,rear,queue[];
public Optimal(int SIZE)
{
p=new int[SIZE];
q= new int[SIZE];
a=new int[SIZE];
w=new int[SIZE][SIZE];
c=new int[SIZE][SIZE];
r=new int[SIZE][SIZE];
queue=new int[SIZE];
front=rear=-1;
}
/* This function returns a value in the range r[i][j-1] to r[i+1][j] SO that the cost c[i][k-1] + c[k][j]
isminimum */
/*This function builds the tree from the tables made by the OBST function */
queue[++rear] =
0; queue[++rear]
= n; while(front
!= rear)
{
i=queue[++front];
j=queue[++front];
k= r[i][j];
System.out.print("\n);
if (r[i][k-1] != 0)
{
System.out.print(" "+r[i][k-]);
queue[++rear] = i;
queue[++rear] = k-1;
}
else
System.out.print(" -");
if(r[k][j] != 0)
{
System.out.print("
"+r[k][j]
);queue[++rear] = k;
queue[++rear] = j;
}
else
System.out.print(" -");
}
System.out.println("\n");
}
}
/* This is the main function
*/class OBSTDemo
{
public static void main (String[] args )throws IOException,NullPointerException
{
Optimal obj=new
Optimal(10);int i;
System.out.print("\n Optimal Binary Search Tree
\n");System.out.print("\n Enter the number of
nodes "); obj.n=getInt();
System.out.print("\n Enter the data as ... \n");
for (i=1;i<=obj.n;i++)
{
System.out.print("\n
a["+i+"]");obj.a[i]=getInt();
}
for (i=1 ; i<=obj.n ; i++)
{
System.out.println("p["+i+"]");
obj.p[i]=getInt();
}
for (i=0 ; i<=obj.n ; i++)
{
System.out.print("q["+i+"]");
obj.q[i]=getInt();
}
obj.OBST();
obj.build_tree();
}
public static String getString() throws IOException
{
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader b = new BufferedReader(input);
String str = b.readLine();//reading the string from
consolereturn str;
}
public static char getChar() throws IOException
{
String str = getString();
return str.charAt(0);//reading first char of console string
}
public static int getInt() throws IOException
{
String str = getString();
return Integer.parseInt(str);//converting console string to numeric value
}
}
OUTPUT:
Optimal Binary Search Tree Enter the number of
nodes 4Enter the data as ....
a[1] 1
a[2] 2
a[3] 3
a[4] 4
p[1] 3
p[2] 3
p[3] 1
p[4] 1
q[0] 2
q[1] 3
q[2] 1
q[3] 1
q[4] 1
The Optimal Binary Search Tree For The Given Nodes Is ....