0% found this document useful (0 votes)
2 views14 pages

Min Max

The document contains multiple Java implementations of algorithms including Min-Max, Binary Search, Defective Chess Board, Knapsack, Sum of Subsets, NQueens, BFS, DFS, Bin Packing, Kruskal's Algorithm, Transitive Closure, and Network Flow Algorithm. Each algorithm is presented with its respective class structure, methods, and main function for execution. The document serves as a comprehensive reference for various algorithmic techniques and their implementations in Java.

Uploaded by

raavihema3
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)
2 views14 pages

Min Max

The document contains multiple Java implementations of algorithms including Min-Max, Binary Search, Defective Chess Board, Knapsack, Sum of Subsets, NQueens, BFS, DFS, Bin Packing, Kruskal's Algorithm, Transitive Closure, and Network Flow Algorithm. Each algorithm is presented with its respective class structure, methods, and main function for execution. The document serves as a comprehensive reference for various algorithmic techniques and their implementations in Java.

Uploaded by

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

Min Max:

import java.util.*;

public class MINMAX {

static int[] a = new int[20];

static int min = Integer.MIN_VALUE;

static int max = Integer.MAX_VALUE;

static int mid;

static void MinMax(int i, int j) {

if(i == j) {

min = a[i];

max = a[j];

else if(i == j-1) {

if(a[i] < a[j]) {

min = a[i];

max = a[j];

else {

min = a[j];

max = a[i];

else {

mid = (i+j)/2;

MinMax(i,mid);

int min1 = min;

int max1 = max;

MinMax(mid+1,j);

if(min1 < min)

min = min1;

if(max1 > max)

max = max1;

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter no.of elements:");


int n = sc.nextInt();

System.out.print("Enter Array elements:");

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

a[i] = sc.nextInt();

MinMax(0,n-1);

System.out.println("Minimum Value:" + min + " " + "Maximum Value:" + max);

Binary Search:

class BinarySearch{

public static int binarySearch(int arr[], int first, int last, int key){

if (last>=first){

int mid = first + (last - first)/2;

if (arr[mid] == key){

return mid;

if (arr[mid] > key){

return binarySearch(arr, first, mid-1, key);

}else{

return binarySearch(arr, mid+1, last, key);

return -1;

public static void main(String args[]){

int arr[] = {10,20,30,40,50};

int key = 30;

int last=arr.length-1;

int result = binarySearch(arr,0,last,key);

if (result == -1)

System.out.println("Element is not found!");

else

System.out.println("Element is found at index: "+result);

Defective Chess Board:


public class DefectiveChessBoard {

public static void findDefective(int[][] board,int x,int y, int size) {

if(size == 1) {

if(board[x][y] == 1)

System.out.println("Defective Square is at " + x + " " + y);

return;

int mid = size / 2;

if(board[x+mid-1][y+mid-1] == 1)

findDefective(board,x,y,mid);

else if(board[x+mid][y+mid-1] == 1)

findDefective(board,x+mid,y,mid);

else

findDefective(board,x+mid,y+mid,mid);

public static void main(String[] args) {

int[][] chessBoard = { {1,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}};

int n = chessBoard.length;

findDefective(chessBoard,0,0,n);

Knapsack:

public class KnapSack {

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

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

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

for (int w = 1; w <= W; w++) {

if (wt[i-1] <= w) {

V[i][w] = Math.max(V[i-1][w], V[i-1][w - wt[i-1]] + val[i-1]);

} else {

V[i][w] = V[i-1][w];

return V[n][W];

}
public static void main(String[] args) {

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

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

int W = 50;

int n = val.length;

int maxProfit = knapSack(W, wt, val, n);

System.out.println("Maximum Profit in Knapsack: " + maxProfit);

Sum of Subsets:

import java.util.*;

public class SS {

public static void findSubsetSums(int[] a, int target) {

List<Integer> currentSubset = new ArrayList<>();

backtrack(a, target, 0, currentSubset, 0);

private static void backtrack(int[] a, int target, int Start, List<Integer> currentSubset, int currentSum) {

if(currentSum == target) {

System.out.println(currentSubset);

return;

for(int i = Start; i < a.length; i++) {

currentSubset.add(a[i]);

backtrack(a, target, i+1, currentSubset, currentSum+a[i]);

currentSubset.remove(currentSubset.size()-1);

public static void main(String[] args) {

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

int target = 5;

System.out.println("Subsets that sum upto " + target + ":");

findSubsetSums(a, target);

NQueens:

import java.util.*;

public class NQueens {


public static boolean solveQueens(int n) {

int[] board = new int[n];

return solveQueensUtil(board, 0, n);

private static boolean solveQueensUtil(int[] board, int row, int n) {

if(row == n) {

printSolution(board,n);

return true;

boolean result = false;

for(int col = 0; col < n; col++) {

if(isSafe(board, row, col, n)) {

board[row] = col;

result = solveQueensUtil(board, row+1, n) || result;

board[row] = -1;

return result;

private static void printSolution(int[] board, int n) {

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

for(int j = 0; j < n; j++) {

if(board[i] == j)

System.out.print("Q");

else

System.out.print(" . ");

System.out.println();

System.out.println();

private static boolean isSafe(int[] board, int row, int col, int n) {

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

if(board[i] == col || Math.abs(board[i]-col) == Math.abs(i-row))

return false;

}
return true;

public static void main(String[] args) {

int n = 4;

if(!solveQueens(n))

System.out.println("Solution doesnot exist");

BFS:

import java.util.*;

class Graph {

private int vertices;

private LinkedList<Integer>[] adjList;

Graph(int V) {

vertices = V;

adjList = new LinkedList[V];

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

adjList[i] = new LinkedList<Integer>();

void addEdge(int V, int w) {

adjList[V].add(w);

void BFS(int startVertex) {

boolean[] visited = new boolean[vertices];

LinkedList<Integer> queue = new LinkedList<>();

visited[startVertex] = true;

queue.add(startVertex);

while(!queue.isEmpty()) {

int vertex = queue.poll();

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

Iterator<Integer> iterator = adjList[vertex].iterator();

while(iterator.hasNext()) {

int adjVertex = iterator.next();

if(!visited[adjVertex]) {

visited[adjVertex] = true;

queue.add(adjVertex);

}
}

public class BFSExample {

public static void main(String[] args) {

Graph g = new Graph(6);

g.addEdge(0,1);

g.addEdge(0,2);

g.addEdge(1,3);

g.addEdge(1,4);

g.addEdge(2,5);

System.out.println("Breadth First Traversal Starting from vertex 0");

g.BFS(0);

DFS:

import java.util.*;

public class Graph {

private Map<Integer, List<Integer>> adjList;

public Graph() {

adjList = new HashMap<>();

public void addVertex(int vertex) {

adjList.putIfAbsent(vertex,new ArrayList<>());

public void addEdge(int src,int dest) {

adjList.get(src).add(dest);

adjList.get(dest).add(src);

public void DFS(int start) {

Set<Integer> visited = new HashSet<>();

DFSUtil(start,visited);

private void DFSUtil(int vertex,Set<Integer> visited) {

visited.add(vertex);

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


for(int neighbour:adjList.get(vertex)) {

if(!visited.contains(neighbour)) {

DFSUtil(neighbour,visited);

public static void main(String args[]) {

Graph g=new Graph();

g.addVertex(0);

g.addVertex(1);

g.addVertex(2);

g.addVertex(3);

g.addVertex(4);

g.addVertex(5);

g.addEdge(0,1);

g.addEdge(0,2);

g.addEdge(1,3);

g.addEdge(2,4);

g.addEdge(3,5);

System.out.println("DFS starting from vertex 0 ");

g.DFS(0);

Bin Packing:

import java.util.*;

public class BinPacking {

static void binpacking(int arr[], int n, int size) {

int binCount = 1;

int spaceLeft = size;

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

if (arr[i] <= spaceLeft) {

spaceLeft -= arr[i];

} else {

binCount++;

spaceLeft = size - arr[i];

}
System.out.println("Number of bins required: " + binCount);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.println("Bin Packing Algorithm using Next Fit");

System.out.print("Enter number of items: ");

int n = sc.nextInt();

int[] arr = new int[n];

System.out.println("Enter the sizes of " + n + " items:");

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

arr[i] = sc.nextInt();

System.out.print("Enter bin size: ");

int size = sc.nextInt();

binpacking(arr, n, size);

Kruskal algorithm:

import java.util.*;

class Edge implements Comparable<Edge>

int src, dest, weight;

public Edge(int src, int dest, int weight)

this.src = src;

this.dest = dest;

this.weight = weight;

public int compareTo(Edge compareEdge)

return this.weight - compareEdge.weight;

class Subset

int parent, rank;

}
public class KruskalsAlgorithm

int V, E;

Edge[] edges;

public KruskalsAlgorithm(int v, int e)

V = v;

E = e;

edges = new Edge[E];

int find(Subset subsets[], int i)

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

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

return subsets[i].parent;

void union(Subset subsets[], int x, int y)

int rootX = find(subsets, x);

int rootY = find(subsets, y);

if (subsets[rootX].rank < subsets[rootY].rank)

subsets[rootX].parent = rootY;

else if (subsets[rootX].rank > subsets[rootY].rank)

subsets[rootY].parent = rootX;

else {

subsets[rootY].parent = rootX;

subsets[rootX].rank++;

void kruskalMST()

Edge[] result = new Edge[V - 1];

int e = 0;

int i = 0;

Arrays.sort(edges);

Subset[] subsets = new Subset[V];

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


subsets[v] = new Subset();

subsets[v].parent = v;

subsets[v].rank = 0;

while (e < V - 1 && i < E)

Edge nextEdge = edges[i++];

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

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

if (x != y) {

result[e++] = nextEdge;

union(subsets, x, y);

System.out.println("Edges in the Minimum Spanning Tree:");

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

System.out.println(result[i].src + " - " + result[i].dest + " : " + result[i].weight);

public static void main(String[] args)

int V = 4;

int E = 5;

KruskalsAlgorithm graph = new KruskalsAlgorithm(V, E);

graph.edges[0] = new Edge(0, 1, 10);

graph.edges[1] = new Edge(0, 2, 6);

graph.edges[2] = new Edge(0, 3, 5);

graph.edges[3] = new Edge(1, 3, 15);

graph.edges[4] = new Edge(2, 3, 4);

graph.kruskalMST();

Transitive closure:

public class TransitiveClosure {

static final int V = 4;

void transitiveClosure(int[][] graph) {

int[][] reach = new int[V][V];


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

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

reach[i][j] = graph[i][j];

for (int k = 0; k < V; k++) {

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

for (int j = 0; j < V; j++) {

reach[i][j] = (reach[i][j] != 0) || (reach[i][k] != 0 && reach[k][j] != 0) ? 1 : 0;

printMatrix(reach);

void printMatrix(int matrix[][]){

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

for (int j = 0; j < V; j++) {

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

System.out.println();

public static void main(String[] args) {

TransitiveClosure tc = new TransitiveClosure();

int[][] graph = {

{1, 1, 0, 1},

{0, 1, 1, 0},

{0, 0, 1, 1},

{0, 0, 0, 1}

};

tc.transitiveClosure(graph);

Network flow algorithm:

import java.util.*;

public class MaxFlow {

static final int V = 6;

boolean bfs(int[][] residualGraph, int s, int t, int[] parent) {

boolean[] visited = new boolean[V];


Queue<Integer> queue = new LinkedList<>();

queue.add(s);

visited[s] = true;

parent[s] = -1;

while (!queue.isEmpty()) {

int u = queue.poll();

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

if (!visited[v] && residualGraph[u][v] > 0) {

queue.add(v);

parent[v] = u;

visited[v] = true;

return visited[t];

int fordFulkerson(int[][] graph, int s, int t) {

int u, v;

int[][] residualGraph = new int[V][V];

for (u = 0; u < V; u++) {

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

residualGraph[u][v] = graph[u][v];

int[] parent = new int[V];

int maxFlow = 0;

while (bfs(residualGraph, s, t, parent)) {

int pathFlow = Integer.MAX_VALUE;

for (v = t; v != s; v = parent[v]) {

u = parent[v];

pathFlow = Math.min(pathFlow, residualGraph[u][v]);

for (v = t; v != s; v = parent[v]) {

u = parent[v];

residualGraph[u][v] -= pathFlow;

residualGraph[v][u] += pathFlow;

}
maxFlow += pathFlow;

return maxFlow;

public static void main(String[] args) {

MaxFlow m = new MaxFlow();

int[][] graph = {

{0, 16, 13, 0, 0, 0},

{0, 0, 10, 12, 0, 0},

{0, 4, 0, 0, 14, 0},

{0, 0, 9, 0, 0, 20},

{0, 0, 0, 7, 0, 4},

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

};

System.out.println("The maximum possible flow is: " + m.fordFulkerson(graph, 0, 5));

You might also like