Professional Documents
Culture Documents
----------------------------------------------------------------------------------------------
B.Tech III YEAR I SEMESTER(R16) Lab
Manual
LIST OF PROGRAMS
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.
4. ii) Write a. java program to implement the bfs algorithm for a graph.
queens problem.
6. Write a java program to implement the backtracking algorithm for the sum of
subsets problem.
with deadlines.
9. Write a java program to implement Dijkstra’s algorithm for the Single source shortest
path problem.
10. Write a java program that implements Prim’s algorithm to generate minimum cost
spanning tree.
11. Write a java program that implements Kruskal’s algorithm to generate minimum cost
spanning tree
12. Write a java program to implement Floyd’s algorithm for the all pairs shortest path
problem.
13. Write a java program to implement Dynamic Programming algorithm for the
14. Write a java program to implement Dynamic Programming algorithm for the
1. Write a java program to implement Quick sort algorithm for sorting a list of
PROGRAM:
import java.util.Scanner;
int temp;
while (i <= j)
i++;
B.Tech III YEAR I SEMESTER(R16) Lab
Manual
j--;
if (i <= j)
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
if (low < j)
if (i < high)
quickSort(arr, i, high);
int n, i;
elements"); n = scan.nextInt();
arr[i] = scan.nextInt();
sort(arr);
System.out.print(arr[i]+" ");
System.out.println();
} }
OUTPUT:
2. Write a java program to implement Merge sort algorithm for sorting a list of integers in
ascending order.
PROGRAM:
import java.util.Scanner;
/* Class MergeSort */
if (N <= 1)
return;
/ recursively sort
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
a[low + k] = temp[k];
/* Main method */
int n, i;
elements"); n = scan.nextInt();
/* Accept elements */
arr[i] = scan.nextInt();
sort(arr, 0, n);
System.out.print(arr[i]+" ");
System.out.println();
OUTPUT:
PROGRAM:
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
public DFS()
int i = source;
System.out.print(element + "\t");
visited[source] = 1;
stack.push(source);
while (!stack.isEmpty())
element = stack.peek();
i = element;
stack.push(i);
visited[i] = 1;
element = i;
i = 1;
System.out.print(element + "\t");
continue;
i++;
stack.pop();
try
= scanner.nextInt();
number_of_nodes; i++)
adjacency_matrix[i][j] = scanner.nextInt();
dfs.dfs(adjacency_matrix, source);
}catch(InputMismatchException inputMismatch)
scanner.close();
OUTPUT:
PROGRAM:
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public BFS()
int i, element;
visited[source] = 1;
queue.add(source);
while (!queue.isEmpty())
element = queue.remove();
i = element;
System.out.print(i + "\t");
queue.add(i);
visited[i] = 1;
i++;
try
number_no_nodes = scanner.nextInt();
number_no_nodes; i++)
adjacency_matrix[i][j] = scanner.nextInt();
bfs.bfs(adjacency_matrix, source);
scanner.close();
OUTPUT:
5. Write a java programs to implement backtracking algorithm for the N-queens problem.
PROGRAM:
backtracking */
final int N = 4;
+ " ");
System.out.println();
int i, j;
if (board[row][i] == 1)
return false;
if (board[i][j] == 1)
return false;
if (board[i][j] == 1)
return false;
return true;
Queen problem */
if (col >= N)
return true;
board[i][col] */
if (isSafe(board, i, col))
board[i][col] = 1;
return true;
board[i][col] = 0; // BACKTRACK
return false;
feasible solutions.*/
boolean solveNQ()
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
if (solveNQUtil(board, 0) == false)
return false;
printSolution(board);
return true;
NQueenProblem(); Queen.solveNQ();
OUTPUT:
6. Write a java program to implement the backtracking algorithm for the sum of subsets problem.
PROGRAM:
int[] input = { 1, 2, 3, 4 };
int targetSum = 7;
subSetSum.findSubSets(input, targetSum);
this.set = set;
this.numOfElements = set.length;
this.targetSum = targetSum;
quicksort(set, 0, numOfElements-1);
int sumOfAllElements = 0;
sumOfAllElements += element;
findSubSets(0, 0, sumOfAllElements);
print();
/ ensures selecting
/ the next element is useful and the total sum by including next
/ now exploring the other path: not Selecting the element at index:
/ 'index'
selectedElements[index] = 0;
/ the next element is useful and the total sum by including next
/ sum of all the elements by excluding the current element may achieve
/ the target sum, if in case the resultant sum is less than the target
if (selectedElements[i] == 1) {
System.out.print(set[i]+" ");
System.out.println();
swap(arr,pIndex,i);
pIndex++;} }
swap(arr,pIndex,end);
return pIndex;
arr[index1] = arr[index2];
arr[index2] = temp;
}}
OUTPUT:
7. Write a java program to implement the backtracking algorithm for the Hamiltonian
Circuits problem.
PROBLEM:
class HamiltonianCycle
final int V = 5;
int path[];
if (graph[path[pos - 1]][v] == 0)
return false;
of size V */
if (path[i] == v)
return false;
return true;
cycle problem */
Hamiltonian Cycle */
if (pos == V)
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
Hamiltonian Cycle */
path[pos] = v;
return true;
then remove it */
path[pos] = -1;
return false;
path[i] = -1;
undirected */
path[0] = 0;
return 0;
printSolution(path);
return 1;
/ complete cycle
HamiltonianCycle hamiltonian =
new HamiltonianCycle();
(0)--(1)--(2)
| /\ |
|/ \ |
|/ \|
(3)-------(4) */
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0},
};
hamiltonian.hamCycle(graph1);
(0)-- (1)--(2)
| /\ |
| / \ |
|/ \|
(3) (4) */
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
};
hamiltonian.hamCycle(graph2);
OUTPUT:
8. Write a java program to implement greedy algorithm for job sequencing with deadlines
PROGRAM:
import java.util.*;
class job
/*************default constructor**************/
job()
p=0;
d=0;
v=0;
p=x;
d=y;
v=z;
class js
static int n;
for(int i=0;i<n;++i)
if(jb[i].p==x)
return i;
return 0;
n=scr.nextInt();
for(int i=0;i<n;++i)
int p=scr.nextInt();
int d=scr.nextInt();
if(max<d)
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;
for(int i=0;i<n;++i)
int count;
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)
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;
} // end of if
} //end of inner
for
/******************************calculating max
for(int i=0;i<max;++i)
profit+=hold[i];
}//end class
OUTPUT:
70 2
12 1
18 2
35 1
9. Write a java program to implement Dijkstra’s algorithm for the Single source shortest path
problem.
PROGRAM:
import java.util.*;
int i,minpos=1,k,c,minimum;
for(i=1;i<=n;i++)
flag[i]=0;
this.distance[i]=this.cost[s][i];
c=2;
while(c<=n)
minimum=99;
for(k=1;k<=n;k++)
minimum=this.distance[i];
minpos=k;
flag[minpos]=1;
c++;
for(k=1;k<=n;k++)
this.distance[k]=this.distance[minpos]+this.cost[minpos][k];
int nodes,source,i,j;
nodes = in.nextInt();
for(i=1;i<=nodes;i++)
for(j=1;j<=nodes;j++)
{d.cost[i][j]=in.nextInt();
if(d.cost[i][j]==0)
d.cost[i][j]=999;
source=in.nextInt();
d.calc(nodes,source);
System.out.println("The Shortest Path from Source \t"+source+"\t to all other vertices are : \n");
for(i=1;i<=nodes;i++)
if(i!=source)
OUTPUT:
10. Write a java program that implements Prim’s algorithm to generate minimum cost spanning
tree.
PROGRAM:
import java.util.InputMismatchException;
import java.util.Scanner;
this.numberofvertices = numberofvertices;
int count = 0;
if (unsettled[index])
count++;
return count;
int evaluationVertex;
this.adjacencyMatrix[source][destination] = adjacencyMatrix[source][destination];
key[index] = INFINITE;
key[1] = 0;
unsettled[1] = true;
parent[1] = 1;
while (getUnsettledCount(unsettled) != 0)
evaluationVertex = getMimumKeyVertexFromUnsettled(unsettled);
unsettled[evaluationVertex] = false;
settled[evaluationVertex] = true;
evaluateNeighbours(evaluationVertex);
int node = 0;
node = vertex;
min = key[vertex];
return node;
if (settled[destinationvertex] == false)
if (adjacencyMatrix[evaluationVertex][destinationvertex] != INFINITE)
key[destinationvertex] = adjacencyMatrix[evaluationVertex][destinationvertex];
parent[destinationvertex] = evaluationVertex;
unsettled[destinationvertex] = true;
int adjacency_matrix[][];
int number_of_vertices;
try
number_of_vertices = scan.nextInt();
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
adjacency_matrix[i][j] = 0;
continue;
if (adjacency_matrix[i][j] == 0)
adjacency_matrix[i][j] = INFINITE;
prims.primsAlgorithm(adjacency_matrix);
prims.printMST();
scan.close();
OUTPUT:
11. Write a java program that implements Kruskal’s algorithm to generate minimum cost
spanning tree
PROGRAM:
import java.util.*;
import java.lang.*;
import java.io.*;
class Graph
return this.weight-compareEdge.weight;
};
class subset
};
V = v;
E = e;
compression) if (subsets[i].parent != i)
return subsets[i].parent;
/ (Union by Rank)
subsets[xroot].parent = yroot;
subsets[yroot].parent = xroot;
else
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
void KruskalMST()
Edge result[] = new Edge[V]; // Tnis will store the resultant MST
Arrays.sort(edge);
i<V; ++i)
subsets[i]=new subset();
subsets[v].parent = v;
subsets[v].rank = 0;
while (e < V - 1)
next_edge = edge[i++];
if (x != y)
result[e++] = next_edge;
Union(subsets, x, y);
System.out.println(result[i].src+" -- " +
// Driver Program
10
0-------- 1
|\ |
6| 5\ |15
|\ |
2--------3
4 */
graph.edge[0].src = 0;
graph.edge[0].dest = 1;
graph.edge[0].weight = 10;
graph.edge[1].src = 0;
graph.edge[1].dest = 2;
graph.edge[1].weight = 6;
graph.edge[2].src = 0;
graph.edge[2].dest = 3;
graph.edge[2].weight = 5;
graph.edge[3].src = 1;
graph.edge[3].dest = 3;
graph.edge[3].weight = 15;
graph.edge[4].src = 2;
graph.edge[4].dest = 3;
graph.edge[4].weight = 4;
graph.KruskalMST();
OUTPUT:
D:\DAA>javac KruskalGraph.java
D:\DAA>java KruskalGraph
2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
12.Write a java program to implement Floyd’s algorithm for the all pairs shortest path problem.
PROGRAM:
if (path[v][u] == v)
return;
printPath(path, v, path[v][u]);
System.out.println(u + ")");
/ (shortest-cost/shortest route)
/ of the edge
cost[v][u] = adjMatrix[v][u];
if (v == u)
path[v][u] = 0;
path[v][u] = v;
else
path[v][u] = -1;
// run Floyd-Warshell
if (cost[v][k] != Integer.MAX_VALUE
path[v][u] = path[k][u];
if (cost[v][v] < 0)
return;
final int N = 4;
int M = Integer.MAX_VALUE;
{ 0, M, -2, M },
{ 4, 0, 3, M },
{ M, M, 0, 2 },
{ M, -1, M, 0 }
};
FloydWarshell(adjMatrix, N);
OUTPUT:
D:\DAA>javac FloydWarshell.java
D:\DAA>java FloydWarshell
13. Write a java program to implement Dynamic Programming algorithm for the 0/1 Knapsack
problem
PROGRAM:
int i, w;
if (i==0 || w==0)
K[i][w] = 0;
else
K[i][w] = K[i-1][w];
return K[n][W];
int W = 50;
int n = val.length;
OUTPUT:
D:\DAA>javac Knapsack.java
D:\DAA>java Knapsack
220
14. Write a java program to implement Dynamic Programming algorithm for the Optimal Binary
Search Tree Problem.
PROGRAM:
/ Return minimum
value return min + fsum;
}
// Driver code
public static void main(String[] args) {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = keys.length;
System.out.println("Cost of Optimal BST is " +
optimalSearchTree(keys, freq, n));
}
}
OUTPUT:
D:\DAA>javac OBST.java
D:\DAA>java OBST