0% found this document useful (0 votes)
3 views

INDEX

The document outlines a series of practical programming tasks, each with a specific aim and accompanying Java code. Tasks include implementing algorithms such as Merge Sort, Matrix Multiplication using Divide and Conquer, and various strategies for solving the Knapsack Problem, as well as finding Minimum Spanning Trees using Kruskal's and Prim's algorithms. The document provides detailed code examples for each task, demonstrating the implementation of these algorithms.

Uploaded by

devx.ankitx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

INDEX

The document outlines a series of practical programming tasks, each with a specific aim and accompanying Java code. Tasks include implementing algorithms such as Merge Sort, Matrix Multiplication using Divide and Conquer, and various strategies for solving the Knapsack Problem, as well as finding Minimum Spanning Trees using Kruskal's and Prim's algorithms. The document provides detailed code examples for each task, demonstrating the implementation of these algorithms.

Uploaded by

devx.ankitx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

INDEX

S. No Practical Signature

1 Write a Program to implement Merge


sort
2 Write a Program to implement Matrix
Multiplication using Divide and
Conquer strategy
3 Write a Program to implement
Knapsack Problem using Greedy
Strategy
4 Write a Program to find Minimum
Spanning Tree of a given graph
using Kruskal's Algorithm

5 Write a Program to find Minimum


Spanning Tree of a given graph
using Prims Algorithm
6 Write a Program to implement Floyd
Warshall Algorithm

7 Write a Program to implement


Knapsack Problem using
Dynamic Programming
8 Write a Program to implement N
queens Problem using
Backtracking
9 Write a Program to perform
Travelling Salesman Problem

10 Write a Program to implement


Knapsack Problem using Branch
and Bound

Practical-1
Aim: Write a Program to implement Merge sort
Code:
import java.util.Scanner;
public class MergeSort {
static void merge(int[] arr, int start, int mid, int end) {
int i = start;
int j = mid + 1;
int k = start;
int[] temp = new int[100];
while (i <= mid && j <= end) {
if (arr[i] < arr[j])
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while (i <= mid)
temp[k++] = arr[i++];
while (j <= end)
temp[k++] = arr[j++];
for (i = start; i <= end; i++)
arr[i] = temp[i];
}
static void mergeSort(int[] arr, int start, int end) {
if (start >= end)
return;
int mid = start + (end - start) / 2;
mergeSort(arr, start, mid);
mergeSort(arr, mid + 1, end);
merge(arr, start, mid, end);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.print("Enter the elements of the array: ");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("\nOriginal Array:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\n");
mergeSort(arr, 0, n - 1);
System.out.println("Sorted Array:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\n");
scanner.close();
}
}
Output:

Practical-2
Aim: Write a Program to implement Matrix Multiplication
using Divide and Conquer strategy
Code:
import java.util.Scanner;
public class MatrixMultiplication {
static int[][] createMatrix(int n) {
int[][] temp = new int[n][n];
return temp;
}
static int[][] divideAndConquer(int[][] A, int[][]
B, int n) {
if (n == 1) {
int[][] C = createMatrix(1);
C[0][0] = A[0][0] * B[0][0];
return C;
}
int[][] C = createMatrix(n);
int k = n / 2;
int[][] A11 = createMatrix(k);
int[][] A12 = createMatrix(k);
int[][] A21 = createMatrix(k);
int[][] A22 = createMatrix(k);
int[][] B11 = createMatrix(k);
int[][] B12 = createMatrix(k);
int[][] B21 = createMatrix(k);
int[][] B22 = createMatrix(k);
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
A11[i][j] = A[i][j];
A12[i][j] = A[i][j + k];
A21[i][j] = A[i + k][j];
A22[i][j] = A[i + k][j + k];
B11[i][j] = B[i][j];
B12[i][j] = B[i][j + k];
B21[i][j] = B[i + k][j];
B22[i][j] = B[i + k][j + k];
}
}
int[][] P1 = divideAndConquer(A11, B11, k);
int[][] P2 = divideAndConquer(A12, B21, k);
int[][] P3 = divideAndConquer(A11, B12, k);
int[][] P4 = divideAndConquer(A12, B22, k);
int[][] P5 = divideAndConquer(A21, B11, k);
int[][] P6 = divideAndConquer(A22, B21, k);
int[][] P7 = divideAndConquer(A21, B12, k);
int[][] P8 = divideAndConquer(A22, B22, k);
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
C[i][j] = P1[i][j] + P2[i][j];
C[i][j + k] = P3[i][j] + P4[i][j];
C[i + k][j] = P5[i][j] + P6[i][j];
C[i + k][j + k] = P7[i][j] + P8[i][j];
}
}
return C;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of matrix (in
powers of 2): ");
int size = scanner.nextInt();
int[][] A = createMatrix(size);
int[][] B = createMatrix(size);
int[][] C;
System.out.println("Enter the elements of
matrix A:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
A[i][j] = scanner.nextInt();
}
}
System.out.println("Enter the elements of
matrix B:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
B[i][j] = scanner.nextInt();
}
}
C = divideAndConquer(A, B, size);
System.out.println("The product of matrix A
and B is:");
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
System.out.print(C[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
Output:
Practical-3
Aim: Write a Program to implement Knapsack Problem
using Greedy Strategy
Code:
import java.util.Arrays;
import java.util.Scanner;
class Item {
int value;
int weight;
Item() {}
Item(int value, int weight) {
this.value = value;
this.weight = weight;
}

public class FractionalKnapsack {


static boolean compare(Item a, Item b) {
double r1 = (double) a.value / a.weight;
double r2 = (double) b.value / b.weight;
return r1 > r2;
}
static double fractionalKnapsack(int W, Item[]
arr, int n) {
Arrays.sort(arr, (a, b) -> compare(a, b) ? -1 :
1);
int curWeight = 0;
double finalValue = 0.0;
for (int i = 0; i < n; i++) {
if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalValue += arr[i].value;
} else {
int remain = W - curWeight;
finalValue += arr[i].value * ((double)
remain / arr[i].weight);
break;
}
}
return finalValue;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the capacity of
knapsack: ");
int W = scanner.nextInt();
System.out.print("Enter the number of items:
");
int n = scanner.nextInt();
Item[] arr = new Item[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter the value and
weight of item " + (i + 1) + ": ");
int value = scanner.nextInt();
int weight = scanner.nextInt();
arr[i] = new Item(value, weight);
}
System.out.println();
System.out.println("Maximum value we can
obtain = " + fractionalKnapsack(W, arr, n));
scanner.close();
}
}
Output:
Practical-4
Aim: Write a Program to find Minimum Spanning Tree of
a given graph using Kruskal's Algorithm
Code:
import java.util.*;
class Main {
static boolean compare(List<Integer> a,
List<Integer> b) {
return a.get(2) < b.get(2);
}
static int findParent(List<Integer> parent, int
node) {
if (parent.get(node) == node) {
return node;
}
return parent.set(node, findParent(parent,
parent.get(node)));
}
static void unionSet(int u, int v, List<Integer>
parent, List<Integer> rank) {
u = findParent(parent, u);
v = findParent(parent, v);
if (rank.get(u) < rank.get(v)) {
parent.set(u, v);
} else if (rank.get(v) < rank.get(u)) {
parent.set(v, u);
} else {
parent.set(v, u);
rank.set(u, rank.get(u) + 1);
}
}
static int
minimumSpanningTree(List<List<Integer>>
edges, int n) {
edges.sort((a, b) -> compare(a, b) ? -1 : 1);
List<Integer> parent = new
ArrayList<>(Collections.nCopies(n, 0));
List<Integer> rank = new
ArrayList<>(Collections.nCopies(n, 0));
for (int i = 0; i < n; i++) {
parent.set(i, i);
}
int minWeight = 0;
System.out.println("\nFollowing are the edges
in the constructed MST - ");
for (List<Integer> edge : edges) {
int u = findParent(parent, edge.get(0));
int v = findParent(parent, edge.get(1));
int wt = edge.get(2);
if (u != v) {
minWeight += wt;
unionSet(u, v, parent, rank);
System.out.println(edge.get(0) + " " +
edge.get(1));
}
}
System.out.println();
return minWeight;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of vertices:
");
int n = scanner.nextInt();
System.out.print("Enter number of edges: ");
int m = scanner.nextInt();
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < m; i++) {
System.out.print("Enter the edge and
weight: ");
int u = scanner.nextInt();
int v = scanner.nextInt();
int w = scanner.nextInt();
g.add(Arrays.asList(u, v, w));
}
int cost = minimumSpanningTree(g, n);
System.out.println("Minimum cost of the
spanning tree: " + cost);
scanner.close();
}
}
Output:
Practical-5
Aim: Write a Program to find Minimum Spanning Tree of
a given graph using Prims Algorithm
Code:
import java.util.*;
class Main {
static List<Map.Entry<Integer,
List<Map.Entry<Integer, Integer>>>>
calculatePrimsMST(int n, int m,
List<Map.Entry<Map.Entry<Integer, Integer>,
Integer>> g) {
Map<Integer, List<Map.Entry<Integer,
Integer>>> adj = new HashMap<>();
for (int i = 0; i < g.size(); i++) {
int u = g.get(i).getKey().getKey();
int v = g.get(i).getKey().getValue();
int w = g.get(i).getValue();
adj.computeIfAbsent(u, k -> new
ArrayList<>()).add(new
AbstractMap.SimpleEntry<>(v, w));
adj.computeIfAbsent(v, k -> new
ArrayList<>()).add(new
AbstractMap.SimpleEntry<>(u, w));
}
List<Integer> key = new
ArrayList<>(Collections.nCopies(n + 1,
Integer.MAX_VALUE));
List<Boolean> mst = new
ArrayList<>(Collections.nCopies(n + 1, false));
List<Integer> parent = new
ArrayList<>(Collections.nCopies(n + 1, -1));
key.set(1, 0);
for (int i = 1; i <= n; i++) {
int mini = Integer.MAX_VALUE;
int u = -1;
for (int v = 1; v <= n; v++) {
if (!mst.get(v) && key.get(v) < mini) {
u = v;
mini = key.get(v);
}
}
mst.set(u, true);
for (Map.Entry<Integer, Integer> it :
adj.getOrDefault(u, new ArrayList<>())) {
int v = it.getKey();
int w = it.getValue();
if (!mst.get(v) && key.get(v) > w) {
key.set(v, w);
parent.set(v, u);
}
}
}
List<Map.Entry<Map.Entry<Integer,
Integer>, Integer>> ans = new ArrayList<>();
for (int i = 2; i <= n; i++) {
ans.add(new
AbstractMap.SimpleEntry<>(new
AbstractMap.SimpleEntry<>(parent.get(i), i),
key.get(i)));
}
return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of vertices:
");
int n = scanner.nextInt();
System.out.print("Enter number of edges: ");
int m = scanner.nextInt();
List<Map.Entry<Map.Entry<Integer,
Integer>, Integer>> g = new ArrayList<>();
for (int i = 0; i < m; i++) {
System.out.print("Enter the edge and
weight: ");
int u = scanner.nextInt();
int v = scanner.nextInt();
int w = scanner.nextInt();
g.add(new
AbstractMap.SimpleEntry<>(new
AbstractMap.SimpleEntry<>(u, v), w));
}
List<Map.Entry<Map.Entry<Integer,
Integer>, Integer>> ans = calculatePrimsMST(n,
m, g);
System.out.println("\nMST edges are:");
for (Map.Entry<Map.Entry<Integer, Integer>,
Integer> entry : ans) {
System.out.println(entry.getKey().getKey()
+ " " + entry.getKey().getValue() + " " +
entry.getValue());
}
scanner.close();
}
}
Output:
Practical-6
Aim: Write a Program to implement Floyd Warshall
Algorithm
Code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of vertices:
");
int n = scanner.nextInt();
System.out.print("Enter number of edges: ");
int m = scanner.nextInt();
int[][] g = new int[n + 1][n + 1];
for (int i = 0; i < n + 1; i++) {
Arrays.fill(g[i], Integer.MAX_VALUE);
}
for (int i = 0; i < m; i++) {
System.out.print("Enter the edge and
weight: ");
int u = scanner.nextInt();
int v = scanner.nextInt();
int w =scanner.nextInt();
g[u][v] = w;
}
for (int i = 1; i <= n; i++) {
g[i][i] = 0;
}
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (g[i][k] != Integer.MAX_VALUE &&
g[k][j] != Integer.MAX_VALUE && g[i][k] + g[k][j]
< g[i][j]) {
g[i][j] = g[i][k] + g[k][j];
}
}
}
}
System.out.println("\nDistance Matrix:");
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(g[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
Output:
Practical-7
Aim: Write a Program to implement Knapsack Problem
using Dynamic Programming
Code:
import java.util.Scanner;
public class Main {
static int knapSack(int W, int[] wt, int[] val, int
n) {
int[][] dp = new int[n + 1][W + 1];
for (int i = 0; i <= n; i++) {
for (int w = 0; w <= W; w++) {
if (i == 0 || w == 0)
dp[i][w] = 0;
else if (wt[i - 1] <= w)
dp[i][w] = Math.max(val[i - 1] + dp[i -
1][w - wt[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items:
");
int items = scanner.nextInt();
int[] profit = new int[items];
int[] weight = new int[items];
for (int i = 0; i < items; i++) {
System.out.print("Enter the profit and
weight of item " + (i + 1) + ": ");
profit[i] = scanner.nextInt();
weight[i] = scanner.nextInt();
}
System.out.print("Enter the capacity of the
knapsack: ");
int W = scanner.nextInt();
System.out.println("Maximum profit is: " +
knapSack(W, weight, profit, items));
scanner.close();
}
}

Output:
Practical-8

Aim: Write a Program to implement N queens Problem using


Backtracking
Code:
import java.util.*;
public class Main {
static boolean isSafe(int row, int col, List<String> board, int
n) {
int x = row, y = col;
// Check row
while (y >= 0) {
if (board.get(x).charAt(y) == 'Q')
return false;
y--;
}
// Top left diagonal
x = row;
y = col;
while (x < n && y >= 0) {
if (board.get(x).charAt(y) == 'Q')
return false;
x++;
y--;
}
// Bottom left diagonal
x = row;
y = col;
while (x >= 0 && y >= 0) {
if (board.get(x).charAt(y) == 'Q')
return false;
x--;
y--;
}
return true;
}
static void solve(int col, List<String> board, int n,
List<List<String>> ans) {
if (col == n) {
ans.add(new ArrayList<>(board));
return;
}
for (int row = 0; row < n; row++) {
if (isSafe(row, col, board, n)) {
StringBuilder sb = new
StringBuilder(board.get(row));
sb.setCharAt(col, 'Q');
board.set(row, sb.toString());
solve(col + 1, board, n, ans);
sb.setCharAt(col, '.');
board.set(row, sb.toString());
}
}
}
static List<List<String>> solveNQueens(int n) {
List<String> s = new ArrayList<>();
for (int i = 0; i < n; i++)
s.add(".");
List<String> board = new
ArrayList<>(Collections.nCopies(n, ""));
for (int i = 0; i < n; i++)
board.set(i, s.get(i));
List<List<String>> ans = new ArrayList<>();
solve(0, board, n, ans);
return ans;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
List<List<String>> ans = solveNQueens(n);
int cnt = 1;
for (List<String> i : ans) {
System.out.println("\nSolution no. " + cnt++);
for (String j : i) {
System.out.println(j);
}
System.out.println();
}
scanner.close();
}
}

Output:
Practical-9

Aim: Write a Program to perform Travelling Salesman Problem


Code:
import java.util.*;
public class Main {
static final int V = 4;
static int travellingSalesmanProblem(int[][] graph, int s) {
List<Integer> vertex = new ArrayList<>();
for (int i = 0; i < V; i++) {
if (i != s)
vertex.add(i);
}
int minPath = Integer.MAX_VALUE;
do {
int currentPathWeight = 0;
int k = s;
for (int i = 0; i < vertex.size(); i++) {
currentPathWeight += graph[k][vertex.get(i)];
k = vertex.get(i);
}
currentPathWeight += graph[k][s];
minPath = Math.min(minPath, currentPathWeight);
} while (nextPermutation(vertex));
return minPath;
}
static boolean nextPermutation(List<Integer> arr) {
int i = arr.size() - 2;
while (i >= 0 && arr.get(i) >= arr.get(i + 1)) {
i--;
}
if (i < 0) {
return false;
}
int j = arr.size() - 1;
while (arr.get(j) <= arr.get(i)) {
j--;
}
Collections.swap(arr, i, j);
Collections.reverse(arr.subList(i + 1, arr.size()));
return true;
}
public static void main(String[] args) {
int[][] graph = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int s = 0;
System.out.println("\nShortest Path is: " +
travellingSalesmanProblem(graph, s) + "\n\n");
}
}
Output:
Practical-10

Aim: Write a Program to implement Knapsack Problem using


Branch and Bound
Code:
import java.util.*;
class Item {
float weight;
int value;
Item(float weight, int value) {
this.weight = weight;
this.value = value;
}
}
class Node {
int level, profit, bound;
float weight;
}
public class Main {
static boolean cmp(Item a, Item b) {
double r1 = (double) a.value / a.weight;
double r2 = (double) b.value / b.weight;
return r1 > r2;
}
static int bound(Node u, int n, int W, Item[] arr) {
if (u.weight >= W) return 0;
int profitBound = u.profit;
int j = u.level + 1;
int totWeight = (int) u.weight;
while (j < n && totWeight + arr[j].weight <= W) {
totWeight += arr[j].weight;
profitBound += arr[j].value;
j++;
}
if (j < n) profitBound += (W - totWeight) * arr[j].value /
arr[j].weight;
return profitBound;
}
static int knapsack(int W, Item[] arr, int n) {
Arrays.sort(arr, (a, b) -> Double.compare((double)
b.value / b.weight, (double) a.value / a.weight));
Queue<Node> Q = new LinkedList<>();
Node u = new Node();
Node v = new Node();
u.level = -1;
u.profit = 0;
u.weight = 0;
Q.add(u);
int maxProfit = 0;
while (!Q.isEmpty()) {
u = Q.poll();
if (u.level == -1) v.level = 0;
if (u.level == n - 1) continue;
v.level = u.level + 1;
v.weight = u.weight + arr[v.level].weight;
v.profit = u.profit + arr[v.level].value;
if (v.weight <= W && v.profit > maxProfit) maxProfit =
v.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit) Q.add(v);
v.weight = u.weight;
v.profit = u.profit;
v.bound = bound(v, n, W, arr);
if (v.bound > maxProfit) Q.add(v);
}
return maxProfit;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of items: ");
int n = scanner.nextInt();
Item[] arr = new Item[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter the weight and value of item "
+ (i + 1) + ": ");
float weight = scanner.nextFloat();
int value = scanner.nextInt();
arr[i] = new Item(weight, value);
}
System.out.print("Enter the capacity of knapsack: ");
int W = scanner.nextInt();
System.out.println("Maximum possible profit = " +
knapsack(W, arr, n));
scanner.close();
}
}
Output:

You might also like