You are on page 1of 69

B.

Tech III YEAR I SEMESTER(R16) Lab


Manual

DESIGN AND ANALYSIS OF


ALGORITHMS LAB MANUAL

----------------------------------------------------------------------------------------------
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.

3. i) Write a java program to implement the dfs algorithm for a graph.

4. ii) Write a. java program to implement the bfs algorithm for a graph.

5. Write a java programs to implement backtracking algorithm for the N-

queens problem.

6. Write a java program to implement the backtracking algorithm for the sum of

subsets problem.

7. Write a java program to implement the backtracking algorithm for the

Hamiltonian Circuits problem.

8. Write a java program to implement greedy algorithm for job sequencing

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.

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

13. Write a java program to implement Dynamic Programming algorithm for the

0/1 Knapsack problem.

14. Write a java program to implement Dynamic Programming algorithm for the

Optimal Binary Search Tree Problem.

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

1. Write a java program to implement Quick sort algorithm for sorting a list of

integers in ascending order

PROGRAM:

import java.util.Scanner;

/** Class QuickSort **/

public class QuickSort

/** Quick Sort function **/

public static void sort(int[] arr)

quickSort(arr, 0, arr.length - 1);

/** Quick sort function **/

public static void quickSort(int arr[], int low, int high)

int i = low, j = high;

int temp;

int pivot = arr[(low + high) / 2];

/** partition **/

while (i <= j)

while (arr[i] < pivot)

i++;
B.Tech III YEAR I SEMESTER(R16) Lab
Manual

while (arr[j] > pivot)

j--;

if (i <= j)

/** swap **/

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

i++;

j--;

/** recursively sort lower half **/

if (low < j)

quickSort(arr, low, j);

/** recursively sort upper half **/

if (i < high)

quickSort(arr, i, high);

/** Main method **/

public static void main(String[] args)

Scanner scan = new Scanner( System.in );

System.out.println("Quick Sort Test\n");

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

int n, i;

/** Accept number of elements **/

System.out.println("Enter number of integer

elements"); n = scan.nextInt();

/** Create array of n elements **/

int arr[] = new int[ n ];

/** Accept elements **/

System.out.println("\nEnter "+ n +" integer

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

arr[i] = scan.nextInt();

/** Call method sort **/

sort(arr);

/** Print sorted Array **/

System.out.println("\nElements after sorting ");

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

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

System.out.println();

} }

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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 */

public class MergeSort

/* Merge Sort function */

public static void sort(int[] a, int low, int high)

int N = high - low;

if (N <= 1)

return;

int mid = low + N/2;

/ recursively sort

sort(a, low, mid);

sort(a, mid, high);

/ merge two sorted subarrays

int[] temp = new int[N];

int i = low, j = mid;

for (int k = 0; k < N; k++)

if (i == mid)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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++];

for (int k = 0; k < N; k++)

a[low + k] = temp[k];

/* Main method */

public static void main(String[] args)

Scanner scan = new Scanner( System.in );

System.out.println("Merge Sort Test\n");

int n, i;

/* Accept number of elements */

System.out.println("Enter number of integer

elements"); n = scan.nextInt();

/* Create array of n elements */

int arr[] = new int[ n ];

/* Accept elements */

System.out.println("\nEnter "+ n +" integer elements");

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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

arr[i] = scan.nextInt();

/* Call method sort */

sort(arr, 0, n);

/* Print sorted Array */

System.out.println("\nElements after sorting ");

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

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

System.out.println();

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

3. Write a java program to implement the dfs algorithm for a graph.

PROGRAM:

import java.util.InputMismatchException;

import java.util.Scanner;

import java.util.Stack;

public class DFS

private Stack<Integer> stack;

public DFS()

stack = new Stack<Integer>();

public void dfs(int adjacency_matrix[][], int source)

int number_of_nodes = adjacency_matrix[source].length - 1;

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

int element = source;

int i = source;

System.out.print(element + "\t");

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

visited[source] = 1;

stack.push(source);

while (!stack.isEmpty())

element = stack.peek();

i = element;

while (i <= number_of_nodes)

if (adjacency_matrix[element][i] == 1 && visited[i] == 0)

stack.push(i);

visited[i] = 1;

element = i;

i = 1;

System.out.print(element + "\t");

continue;

i++;

stack.pop();

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

public static void main(String...arg)

int number_of_nodes, source;

Scanner scanner = null;

try

System.out.println("Enter the number of nodes in the

graph"); scanner = new Scanner(System.in); number_of_nodes

= scanner.nextInt();

int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes +

1]; System.out.println("Enter the adjacency matrix"); for (int i = 1; i <=

number_of_nodes; i++)

for (int j = 1; j <= number_of_nodes; j++)

adjacency_matrix[i][j] = scanner.nextInt();

System.out.println("Enter the source for the

graph"); source = scanner.nextInt();

System.out.println("The DFS Traversal for the graph is given by ");

DFS dfs = new DFS();

dfs.dfs(adjacency_matrix, source);

}catch(InputMismatchException inputMismatch)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

System.out.println("Wrong Input format");

scanner.close();

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

4. Write a. java program to implement the bfs algorithm for a graph.

PROGRAM:

import java.util.InputMismatchException;

import java.util.LinkedList;

import java.util.Queue;

import java.util.Scanner;

public class BFS

private Queue<Integer> queue;

public BFS()

queue = new LinkedList<Integer>();

public void bfs(int adjacency_matrix[][], int source)

int number_of_nodes = adjacency_matrix[source].length - 1;

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

int i, element;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

visited[source] = 1;

queue.add(source);

while (!queue.isEmpty())

element = queue.remove();

i = element;

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

while (i <= number_of_nodes)

if (adjacency_matrix[element][i] == 1 && visited[i] == 0)

queue.add(i);

visited[i] = 1;

i++;

public static void main(String... arg)

int number_no_nodes, source;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

Scanner scanner = null;

try

System.out.println("Enter the number of nodes in the

graph"); scanner = new Scanner(System.in);

number_no_nodes = scanner.nextInt();

int adjacency_matrix[][] = new int[number_no_nodes + 1][number_no_nodes +

1]; System.out.println("Enter the adjacency matrix"); for (int i = 1; i <=

number_no_nodes; i++)

for (int j = 1; j <= number_no_nodes; j++)

adjacency_matrix[i][j] = scanner.nextInt();

System.out.println("Enter the source for the

graph"); source = scanner.nextInt();

System.out.println("The BFS traversal of the graph is ");

BFS bfs = new BFS();

bfs.bfs(adjacency_matrix, source);

} catch (InputMismatchException inputMismatch)

System.out.println("Wrong Input Format");

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

scanner.close();

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

5. Write a java programs to implement backtracking algorithm for the N-queens problem.

PROGRAM:

/* Java program to solve N Queen Problem using

backtracking */

public class NQueenProblem

final int N = 4;

/* A utility function to print solution */

void printSolution(int board[][])

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

for (int j = 0; j < N; j++)

System.out.print(" " + board[i][j]

+ " ");

System.out.println();

/* A uStility function to check if a queen can

be placed on board[row][col]. Note that this

function is called when "col" queens are already

placeed in columns from 0 to col -1. So we need

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

to check only left side for attacking queens */

boolean isSafe(int board[][], int row, int col)

int i, j;

/* Check this row on left side */

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

if (board[row][i] == 1)

return false;

/* Check upper diagonal on left side */

for (i=row, j=col; i>=0 && j>=0; i--, j--)

if (board[i][j] == 1)

return false;

/* Check lower diagonal on left side */

for (i=row, j=col; j>=0 && i<N; i++, j--)

if (board[i][j] == 1)

return false;

return true;

/* A recursive utility function to solve N

Queen problem */

boolean solveNQUtil(int board[][], int col)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/* base case: If all queens are placed

then return true */

if (col >= N)

return true;

/* Consider this column and try placing

this queen in all rows one by one */

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

/* Check if queen can be placed on

board[i][col] */

if (isSafe(board, i, col))

/* Place this queen in board[i][col] */

board[i][col] = 1;

/* recur to place rest of the queens */

if (solveNQUtil(board, col + 1) == true)

return true;

/* If placing queen in board[i][col]

doesn't lead to a solution then

remove queen from board[i][col] */

board[i][col] = 0; // BACKTRACK

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/* If queen can not be place in any row in

this colum col, then return false */

return false;

/* This function solves the N Queen problem using

Backtracking. It mainly uses solveNQUtil() to

solve the problem. It returns false if queens

cannot be placed, otherwise return true and

prints placement of queens in the form of 1s.

Please note that there may be more than one

solutions, this function prints one of the

feasible solutions.*/

boolean solveNQ()

int board[][] = {{0, 0, 0, 0},

{0, 0, 0, 0},

{0, 0, 0, 0},

{0, 0, 0, 0}

};

if (solveNQUtil(board, 0) == false)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

System.out.print("Solution does not exist");

return false;

printSolution(board);

return true;

/ driver program to test above function

public static void main(String args[])

NQueenProblem Queen = new

NQueenProblem(); Queen.solveNQ();

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

6. Write a java program to implement the backtracking algorithm for the sum of subsets problem.

PROGRAM:

public class SubSetSum {

public static void main(String[] args) {

int[] input = { 1, 2, 3, 4 };

int targetSum = 7;

SubSetSum subSetSum = new SubSetSum();

subSetSum.findSubSets(input, targetSum);

private int[] set;

private int[] selectedElements;

private int targetSum;

private int numOfElements;

public void findSubSets(int[] set, int targetSum) {

this.set = set;

this.numOfElements = set.length;

this.targetSum = targetSum;

selectedElements = new int[numOfElements];

quicksort(set, 0, numOfElements-1);

int sumOfAllElements = 0;

for(int element : set){

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

sumOfAllElements += element;

findSubSets(0, 0, sumOfAllElements);

private void findSubSets(int sumTillNow, int index, int sumOfRemaining) {

selectedElements[index] = 1; // selecting element at index : 'index'

if (targetSum == set[index] + sumTillNow) {

print();

/ (sum + set[index] + set[index+1] <= targetSum) : this condition

/ ensures selecting

/ the next element is useful and the total sum by including next

/ element will not exceed the target sum.

if ((index + 1 < numOfElements) && (sumTillNow + set[index] + set[index + 1] <= targetSum)) {

findSubSets(sumTillNow + set[index], index + 1, sumOfRemaining - set[index]);

/ now exploring the other path: not Selecting the element at index:

/ 'index'

selectedElements[index] = 0;

// (sum + set[index+1] <= targetSum) : this condition ensures selecting

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/ the next element is useful and the total sum by including next

/ element will not exceed the target sum.

/ (sum + sumOfRemaining - set[index] >= targetSum) ensures the total

/ 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

/ sum then exploring this path is of no use

if ((index + 1 < numOfElements) && (sumTillNow + set[index + 1] <= targetSum)

& (sumTillNow + sumOfRemaining - set[index] >= targetSum)) {

findSubSets(sumTillNow, index + 1, sumOfRemaining - set[index]);

private void print() {

for (int i = 0; i < numOfElements; i++) {

if (selectedElements[i] == 1) {

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

System.out.println();

private void quicksort(int[] arr, int start, int end) {

if (start < end) {

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

swap(arr, (start + (end - start) / 2), end);

int pIndex = partition(arr, start, end);

quicksort(arr, start, pIndex - 1);

quicksort(arr, pIndex + 1, end);

private int partition(int[] arr, int start, int end) {

int pIndex = start, pivot = arr[end];

for (int i = start; i < end; i++) {

if (arr[i] < pivot) {

swap(arr,pIndex,i);

pIndex++;} }

swap(arr,pIndex,end);

return pIndex;

}private void swap(int[] arr, int index1, int index2)

{ int temp = arr[index1];

arr[index1] = arr[index2];

arr[index2] = temp;

}}

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

7. Write a java program to implement the backtracking algorithm for the Hamiltonian
Circuits problem.

PROBLEM:

/* Java program for solution of Hamiltonian Cycle

problem using backtracking */

class HamiltonianCycle

final int V = 5;

int path[];

/* A utility function to check if the vertex v can be

added at index 'pos'in the Hamiltonian Cycle

constructed so far (stored in 'path[]') */

boolean isSafe(int v, int graph[][], int path[], int pos)

/* Check if this vertex is an adjacent vertex of

the previously added vertex. */

if (graph[path[pos - 1]][v] == 0)

return false;

/* Check if the vertex has already been included.

This step can be optimized by creating an array

of size V */

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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

if (path[i] == v)

return false;

return true;

/* A recursive utility function to solve hamiltonian

cycle problem */

boolean hamCycleUtil(int graph[][], int path[], int pos)

/* base case: If all vertices are included in

Hamiltonian Cycle */

if (pos == V)

/ And if there is an edge from the last included

/ vertex to the first vertex

if (graph[path[pos - 1]][path[0]] == 1)

return true;

else

return false;

// Try different vertices as a next candidate in

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/ Hamiltonian Cycle. We don't try for 0 as we

/ included 0 as starting point in in

hamCycle() for (int v = 1; v < V; v++)

/* Check if this vertex can be added to

Hamiltonian Cycle */

if (isSafe(v, graph, path, pos))

path[pos] = v;

/* recur to construct rest of the path */

if (hamCycleUtil(graph, path, pos + 1) == true)

return true;

/* If adding vertex v doesn't lead to a solution,

then remove it */

path[pos] = -1;

/* If no vertex can be added to Hamiltonian Cycle

constructed so far, then return false */

return false;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/* This function solves the Hamiltonian Cycle problem using

Backtracking. It mainly uses hamCycleUtil() to solve the

problem. It returns false if there is no Hamiltonian Cycle

possible, otherwise return true and prints the path.

Please note that there may be more than one solutions,

this function prints one of the feasible solutions. */

int hamCycle(int graph[][])

path = new int[V];

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

path[i] = -1;

/* Let us put vertex 0 as the first vertex in the path.

If there is a Hamiltonian Cycle, then the path can be

started from any point of the cycle as the graph is

undirected */

path[0] = 0;

if (hamCycleUtil(graph, path, 1) == false)

System.out.println("\nSolution does not exist");

return 0;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

printSolution(path);

return 1;

/* A utility function to print solution */

void printSolution(int path[])

System.out.println("Solution Exists: Following" +

" is one Hamiltonian

Cycle"); for (int i = 0; i < V; i++)

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

/ Let us print the first vertex again to show the

/ complete cycle

System.out.println(" " + path[0] + " ");

/driver program to test above function

public static void main(String args[])

HamiltonianCycle hamiltonian =

new HamiltonianCycle();

/* Let us create the following graph

(0)--(1)--(2)

| /\ |

|/ \ |

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

|/ \|

(3)-------(4) */

int graph1[][] = {{0, 1, 0, 1, 0},

{1, 0, 1, 1, 1},

{0, 1, 0, 0, 1},

{1, 1, 0, 0, 1},

{0, 1, 1, 1, 0},

};

/ Print the solution

hamiltonian.hamCycle(graph1);

/* Let us create the following graph

(0)-- (1)--(2)

| /\ |

| / \ |

|/ \|

(3) (4) */

int graph2[][] = {{0, 1, 0, 1, 0},

{1, 0, 1, 1, 1},

{0, 1, 0, 0, 1},

{1, 1, 0, 0, 0},

{0, 1, 1, 0, 0},

};

/ Print the solution

hamiltonian.hamCycle(graph2);

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

8. Write a java program to implement greedy algorithm for job sequencing with deadlines

PROGRAM:

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

/*************default constructor**************/

job()

p=0;

d=0;

v=0;

job(int x,int y,int z) // parameterised constructor

p=x;

d=y;

v=z;

class js

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab Manual

static int n;

static int out(job jb[],int x)

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

if(jb[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];

/***********************Accepting job from user*************************/

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

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

//accepted jobs from user

/*************************Sorting in increasing orser of deadlines*************************/

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

/******************************Displaying the jobs to the user***********************/

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];

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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

hold[i]=0;

/*****************************Process of job sequencing begins*************************/

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;

} // end of if

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

} //end of inner

for }// end of outer

for

/******************************job sequencing process ends******************************/

/******************************calculating max

profit**********************************/ int profit=0;

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

profit+=hold[i];

System.out.println("The maximum profit is "+profit);

}//end main method

}//end class

OUTPUT:

Enter the number of jobs

Enter profit and deadline(p d)

70 2

Enter profit and deadline(p d)

12 1

Enter profit and deadline(p d)

18 2

Enter profit and deadline(p d)

35 1

The jobs are as follows

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

Job 0 Profit = 12 Deadline = 1

Job 1 Profit = 35 Deadline = 1

Job 2 Profit = 18 Deadline = 2

Job 3 Profit = 70 Deadline = 2

The maximum profit is 105

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

9. Write a java program to implement Dijkstra’s algorithm for the Single source shortest path
problem.

PROGRAM:

import java.util.*;

public class Dijkstra

public int distance[] = new int[10];

public int cost[][] = new int[10][10];

public void calc(int n,int s)

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

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++)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

if(this.distance[k]<minimum && flag[k]!=1)

minimum=this.distance[i];

minpos=k;

flag[minpos]=1;

c++;

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

if(this.distance[minpos]+this.cost[minpos][k] < this.distance[k] && flag[k]!=1 )

this.distance[k]=this.distance[minpos]+this.cost[minpos][k];

public static void main(String args[])

int nodes,source,i,j;

Scanner in = new Scanner(System.in);

System.out.println("Enter the Number of Nodes \n");

nodes = in.nextInt();

Dijkstra d = new Dijkstra();

System.out.println("Enter the Cost Matrix Weights: \n");

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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;

System.out.println("Enter the Source Vertex :\n");

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)

System.out.println("source :"+source+"\t destination :"+i+"\t MinCost is :"+d.distance[i]+"\t");

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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;

public class Prims

private boolean unsettled[];

private boolean settled[];

private int numberofvertices;

private int adjacencyMatrix[][];

private int key[];

public static final int INFINITE = 999;

private int parent[];

public Prims(int numberofvertices)

this.numberofvertices = numberofvertices;

unsettled = new boolean[numberofvertices + 1];

settled = new boolean[numberofvertices + 1];

adjacencyMatrix = new int[numberofvertices + 1][numberofvertices +

1]; key = new int[numberofvertices + 1];

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

parent = new int[numberofvertices + 1];

public int getUnsettledCount(boolean unsettled[])

int count = 0;

for (int index = 0; index < unsettled.length; index++)

if (unsettled[index])

count++;

return count;

public void primsAlgorithm(int adjacencyMatrix[][])

int evaluationVertex;

for (int source = 1; source <= numberofvertices; source++)

for (int destination = 1; destination <= numberofvertices; destination++)

this.adjacencyMatrix[source][destination] = adjacencyMatrix[source][destination];

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

for (int index = 1; index <= numberofvertices; index++)

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);

private int getMimumKeyVertexFromUnsettled(boolean[] unsettled2)

int min = Integer.MAX_VALUE;

int node = 0;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

for (int vertex = 1; vertex <= numberofvertices; vertex++)

if (unsettled[vertex] == true && key[vertex] < min)

node = vertex;

min = key[vertex];

return node;

public void evaluateNeighbours(int evaluationVertex)

for (int destinationvertex = 1; destinationvertex <= numberofvertices; destinationvertex++)

if (settled[destinationvertex] == false)

if (adjacencyMatrix[evaluationVertex][destinationvertex] != INFINITE)

if (adjacencyMatrix[evaluationVertex][destinationvertex] < key[destinationvertex])

key[destinationvertex] = adjacencyMatrix[evaluationVertex][destinationvertex];

parent[destinationvertex] = evaluationVertex;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

unsettled[destinationvertex] = true;

public void printMST()

System.out.println("SOURCE : DESTINATION = WEIGHT");

for (int vertex = 2; vertex <= numberofvertices; vertex++) {

System.out.println(parent[vertex] + "\t:\t" + vertex


+"\t=\t"+ adjacencyMatrix[parent[vertex]][vertex]);

public static void main(String... arg)

int adjacency_matrix[][];

int number_of_vertices;

Scanner scan = new Scanner(System.in);

try

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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

number_of_vertices = scan.nextInt();

adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];

System.out.println("Enter the Weighted Matrix for the graph");

for (int i = 1; i <= number_of_vertices; i++) {

for (int j = 1; j <= number_of_vertices; j++)

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 prims = new Prims(number_of_vertices);

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

prims.primsAlgorithm(adjacency_matrix);

prims.printMST();

} catch (InputMismatchException inputMismatch)

System.out.println("Wrong Input Format");

scan.close();

OUTPUT:

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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

// A class to represent a graph edge class Edge implements Comparable<Edge>

int src, dest, weight;

/ Comparator function used for sorting edges

/ based on their weight

public int compareTo(Edge compareEdge)

return this.weight-compareEdge.weight;

};

// A class to represent a subset for union-find

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

class subset

int parent, rank;

};

int V, E; // V-> no. of vertices & E->no.of edges

Edge edge[]; // collection of all edges

/ Creates a graph with V vertices and E

edges Graph(int v, int e)

V = v;

E = e;

edge = new Edge[E];

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

edge[i] = new Edge();

/ A utility function to find set of an element i

/ (uses path compression technique)

int find(subset subsets[], int i)

/ find root and make root as parent of i (path

compression) if (subsets[i].parent != i)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

subsets[i].parent = find(subsets, subsets[i].parent);

return subsets[i].parent;

/ A function that does union of two sets of x and y

/ (uses union by rank)

void Union(subset subsets[], int x, int y)

int xroot = find(subsets, x);

int yroot = find(subsets, y);

/ Attach smaller rank tree under root of high rank tree

/ (Union by Rank)

if (subsets[xroot].rank < subsets[yroot].rank)

subsets[xroot].parent = yroot;

else if (subsets[xroot].rank > subsets[yroot].rank)

subsets[yroot].parent = xroot;

/ If ranks are same, then make one as root and increment

/ its rank by one

else

subsets[yroot].parent = xroot;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

subsets[xroot].rank++;

/ The main function to construct MST using Kruskal's algorithm

void KruskalMST()

Edge result[] = new Edge[V]; // Tnis will store the resultant MST

int e = 0; // An index variable, used for result[]

int i = 0; // An index variable, used for sorted edges

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

result[i] = new Edge();

/ Step 1: Sort all the edges in non-decreasing order of their

/ weight. If we are not allowed to change the given graph, we

/ can create a copy of array of edges

Arrays.sort(edge);

/ Allocate memory for creating V ssubsets

subset subsets[] = new subset[V]; for(i=0;

i<V; ++i)

subsets[i]=new subset();

/ Create V subsets with single elements

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

for (int v = 0; v < V; ++v)

subsets[v].parent = v;

subsets[v].rank = 0;

i = 0; // Index used to pick next edge

/ Number of edges to be taken is equal to V-1

while (e < V - 1)

/ Step 2: Pick the smallest edge. And increment

/ the index for next iteration

Edge next_edge = new Edge();

next_edge = edge[i++];

int x = find(subsets, next_edge.src);

int y = find(subsets, next_edge.dest);

/ If including this edge does't cause cycle,

/ include it in result and increment the index

/ of result for next edge

if (x != y)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

result[e++] = next_edge;

Union(subsets, x, y);

// Else discard the next_edge

/ print the contents of result[] to display

/ the built MST

System.out.println("Following are the edges in " +

"the constructed MST");

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

System.out.println(result[i].src+" -- " +

result[i].dest+" == " + result[i].weight);

// Driver Program

public static void main (String[] args)

/* Let us create following weighted graph

10

0-------- 1

|\ |

6| 5\ |15

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab Manual

|\ |

2--------3

4 */

int V = 4; // Number of vertices in graph

int E = 5; // Number of edges in graph

Graph graph = new Graph(V, E);

/ add edge 0-1

graph.edge[0].src = 0;

graph.edge[0].dest = 1;

graph.edge[0].weight = 10;

/ add edge 0-2

graph.edge[1].src = 0;

graph.edge[1].dest = 2;

graph.edge[1].weight = 6;

/ add edge 0-3

graph.edge[2].src = 0;

graph.edge[2].dest = 3;

graph.edge[2].weight = 5;

/ add edge 1-3

graph.edge[3].src = 1;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

graph.edge[3].dest = 3;

graph.edge[3].weight = 15;

/ add edge 2-3

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

Following are the edges in the constructed MST

2 -- 3 == 4

0 -- 3 == 5

0 -- 1 == 10

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

12.Write a java program to implement Floyd’s algorithm for the all pairs shortest path problem.

PROGRAM:

public class FloydWarshell

/ Recursive Function to print path of given

/ vertex u from source vertex v

private static void printPath(int[][] path, int v, int u)

if (path[v][u] == v)

return;

printPath(path, v, path[v][u]);

System.out.print(path[v][u] + " ");

/ Function to print the shortest cost with path

/ information between all pairs of vertices

private static void printSolution(int[][] cost, int[][] path, int N)

for (int v = 0; v < N; v++)

for (int u = 0; u < N; u++)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

if (u != v && path[v][u] != -1)

System.out.print("Shortest Path from vertex " + v +

" to vertex " + u + " is (" + v + "

"); printPath(path, v, u);

System.out.println(u + ")");

// Function to run Floyd-Warshell algorithm

public static void FloydWarshell(int[][] adjMatrix, int N)

/ cost[] and parent[] stores shortest-path

/ (shortest-cost/shortest route)

information int[][] cost = new int[N][N];

int[][] path = new int[N][N];

/ initialize cost[] and parent[]

for (int v = 0; v < N; v++)

for (int u = 0; u < N; u++)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/ initally cost would be same as weight

/ of the edge

cost[v][u] = adjMatrix[v][u];

if (v == u)

path[v][u] = 0;

else if (cost[v][u] != Integer.MAX_VALUE)

path[v][u] = v;

else

path[v][u] = -1;

// run Floyd-Warshell

for (int k = 0; k < N; k++)

for (int v = 0; v < N; v++)

for (int u = 0; u < N; u++)

/ If vertex k is on the shortest path from v to u,

/ then update the value of cost[v][u], path[v][u]

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

if (cost[v][k] != Integer.MAX_VALUE

& cost[k][u] != Integer.MAX_VALUE

& (cost[v][k] + cost[k][u] < cost[v][u]))

cost[v][u] = cost[v][k] + cost[k][u];

path[v][u] = path[k][u];

/ if diagonal elements become negative, the

/ graph contains a negative weight cycle

if (cost[v][v] < 0)

System.out.println("Negative Weight Cycle Found!!");

return;

/ Print the shortest path between all pairs of

vertices printSolution(cost, path, N);

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

public static void main(String[] args)

/ Number of vertices in the adjMatrix

final int N = 4;

int M = Integer.MAX_VALUE;

/ given adjacency representation of

matrix int[][] adjMatrix = new int[][]

{ 0, M, -2, M },

{ 4, 0, 3, M },

{ M, M, 0, 2 },

{ M, -1, M, 0 }

};

/ Run Floyd Warshell algorithm

FloydWarshell(adjMatrix, N);

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

OUTPUT:

D:\DAA>javac FloydWarshell.java

D:\DAA>java FloydWarshell

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

13. Write a java program to implement Dynamic Programming algorithm for the 0/1 Knapsack
problem

PROGRAM:

/ A Dynamic Programming based solution for 0-1 Knapsack problem

public class Knapsack

/ A utility function that returns maximum of two integers

static int max(int a, int b) { return (a > b)? a : b; }

/ Returns the maximum value that can be put in a knapsack of capacity W

static int knapSack(int W, int wt[], int val[], int n)

int i, w;

int K[][] = new int[n+1][W+1];

/ Build table K[][] in bottom up manner

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

for (w = 0; w <= W; w++)

if (i==0 || w==0)

K[i][w] = 0;

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

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];

/ Driver program to test above function

public static void main(String args[])

int val[] = new int[]{60, 100, 120};

int wt[] = new int[]{10, 20, 30};

int W = 50;

int n = val.length;

System.out.println(knapSack(W, wt, val, n));

OUTPUT:

D:\DAA>javac Knapsack.java

D:\DAA>java Knapsack

220

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

14. Write a java program to implement Dynamic Programming algorithm for the Optimal Binary
Search Tree Problem.

PROGRAM:

public class OBST


{
/ A recursive function to calculate cost of
/ optimal binary search tree
static int optCost(int freq[], int i, int j)
{
// Base cases
if (j < i) // no elements in this subarray
return 0;
if (j == i) // one element in this subarray
return freq[i];

/ Get sum of freq[i], freq[i+1], ... freq[j]


int fsum = sum(freq, i, j);

/ Initialize minimum value


int min = Integer.MAX_VALUE;

/ One by one consider all elements as root and


/ recursively find cost of the BST, compare the
/ cost with min and update min if needed
for (int r = i; r <= j; ++r)
{
int cost = optCost(freq, i, r-1) +
optCost(freq, r+1, j);
if (cost < min)
min = cost;
}

/ Return minimum
value return min + fsum;
}

/ The main function that calculates minimum cost of


/ a Binary Search Tree. It mainly uses optCost() to
/ find the optimal cost.
static int optimalSearchTree(int keys[], int freq[], int n)
{

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

/ Here array keys[] is assumed to be sorted in


/ increasing order. If keys[] is not sorted, then
/ add code to sort keys, and rearrange freq[]
/ accordingly.
return optCost(freq, 0, n-1);
}

/ A utility function to get sum of array elements


/ freq[i] to freq[j]
static int sum(int freq[], int i, int j)
{
int s = 0;
for (int k = i; k <=j; k++)
s += freq[k];
return s;
}

// 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

Cost of Optimal BST is 142

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY


B.Tech III YEAR I SEMESTER(R16) Lab
Manual

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

You might also like