0% found this document useful (0 votes)
13 views45 pages

Daa Final Edited

The document contains various algorithm implementations in Java, including Depth-First Search (DFS), Breadth-First Search (BFS), Quick Sort, Merge Sort, Fractional Knapsack, Prim's algorithm, Dijkstra's algorithm, All Pairs Shortest Path (APSP), and the Traveling Salesman Problem (TSP). Each algorithm is accompanied by its code and sample output demonstrating its functionality. The algorithms cover fundamental concepts in data structures and graph theory.

Uploaded by

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

Daa Final Edited

The document contains various algorithm implementations in Java, including Depth-First Search (DFS), Breadth-First Search (BFS), Quick Sort, Merge Sort, Fractional Knapsack, Prim's algorithm, Dijkstra's algorithm, All Pairs Shortest Path (APSP), and the Traveling Salesman Problem (TSP). Each algorithm is accompanied by its code and sample output demonstrating its functionality. The algorithms cover fundamental concepts in data structures and graph theory.

Uploaded by

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

DFS ALGORITHM CODE :

public class DFS {

int adj[][] = {

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

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

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

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

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

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

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

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

};

int visited[] = new int[8];

public static void main(String[] args) {

DFS d = new DFS();

d.dfs(2);

public void dfs(int v) {

System.out.println(v);

visited[v] = 1;

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


if (adj[v][j] == 1 && visited[j] == 0) {

dfs(j);

OUTPUT:
2

6
BFS ALGORITHM CODE :

import java.util.LinkedList;

import java.util.Queue;

public class BreadthFirstSearch {

int adj[][] = {

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

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

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

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

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

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

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

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

};

public static void main(String[] args) {

BreadthFirstSearch b = new BreadthFirstSearch();

b.bfs(3, 8);

public void bfs(int v, int n) {

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


int visited[] = new int[n];

int i = v;

visited[i] = 1;

queue.add(i);

while (!queue.isEmpty()) {

int node = queue.remove();

System.out.println(node);

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

if (adj[node][j] == 1 && visited[j] == 0) {

queue.add(j);

visited[j] = 1;

OUTPUT:
3 1 7 0 4 5 6 2
QUICK SORT ALGORITHM CODE :

public class Quicksort {

static void swap(int[] arr, int i, int j) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

static int partition(int[] arr, int low, int high) {

int pivot = arr[high];

int i = low - 1;

for (int j = low; j <= high - 1; j++) {

if (arr[j] < pivot) {

i++;

swap(arr, i, j);

swap(arr, i + 1, high);

return (i + 1);

static void Quicksort(int[] arr, int low, int high) {


if (low < high) {

int pi = partition(arr, low, high);

Quicksort(arr, low, pi - 1);

Quicksort(arr, pi + 1, high);

static void printArray(int[] arr, int size) {

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

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

System.out.println();

public static void main(String[] args) {

int[] arr = {54, 78, 63, 92, 45, 86, 15, 28, 37, 10};

int n = arr.length;

Quicksort(arr, 0, n - 1);

System.out.println("Sorted array:");

printArray(arr, n);

OUTPUT:
Sorted array:

10 15 28 37 45 54 63 78 86 92
MERGE SORT ALGORITHM CODE :

public class MergeSort {

private int[] array;

private int[] tempArray;

private int length;

public MergeSort(int[] array) {

this.array = array;

this.length = array.length;

this.tempArray = new int[length];

mergeSort(0, length - 1);

public void mergeSort(int low, int high) {

if (low < high) {

int mid = (low + high) / 2;

mergeSort(low, mid);

mergeSort(mid + 1, high);

merge(low, mid, high);

public void merge(int low, int mid, int high) {


for (int i = low; i <= high; i++) {

tempArray[i] = array[i];

int i = low;

int j = mid + 1;

int k = low;

while (i <= mid && j <= high) {

if (tempArray[i] <= tempArray[j]) {

array[k] = tempArray[i];

i++;

} else {

array[k] = tempArray[j];

j++;

k++;

while (i <= mid) {

array[k] = tempArray[i];

k++;

i++;

}
}

public void show() {

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

System.out.println(array[i]);

public static void main(String[] args) {

int[] array = {51, 21, 31, 11, 71, 61, 99};

MergeSort mergeSort = new MergeSort(array);

mergeSort.show();

OUTPUT:
11

21

31

51

61

71

99
KNAPSACK FRACTIONAL ALGORITHM CODE :

public class Knapsack {

public void knapsack(int m, int n, int profit[], int weight[], double x[]) {

int i = 0;

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

x[i] = 0.0;

double u = m;

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

if (weight[i] > u) {

break;

x[i] = 1.0;

u = u - weight[i];

if (i < n)

x[i] = u / weight[i];

double totprofit = 0;

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

System.out.println(x[i]);

totprofit += profit[i] * x[i];

System.out.println(totprofit);

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

int n = 3, m = 20;

int weight[] = {18, 15, 10};

int profit[] = {25, 24, 15};

double x[] = new double[n];

Knapsack k = new Knapsack();

k.knapsack(m, n, profit, weight, x);

Output:
1.0

0.13333333333333333

0.0

28.2
PRIMS ALGORITHM CODE :
package prims;

public class Prims {

public int z = Integer.MAX_VALUE;

public int cost[][]={

{z,28,z,z,z,10,z},

{28,z,16,z,z,z,14},

{z,16,z,12,z,z,z},

{z,z,12,z,22,z,18},

{z,z,z,22,z,25,24},

{10,z,z,z,25,z,z},

{z,14,z,18,24,z,z}

};

public int mincost=Integer.MAX_VALUE;

public int n;

public int t[][];

public int near[];

public int k;

public int l;

public Prims()

n = 7;

t = new int[n][2];
near = new int[n];

k = -1;

l = -1;

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

near[i] = -1;

t[i][0] = -1;

t[i][1] = -1;

public int primsalgo()

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

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

if(cost[i][j] < mincost)

mincost = cost[i][j];

k = i;

l = j;

mincost = cost[k][l];

t[0][0] = k;

t[0][1] = l;
for(int i=0;i<n;i++)

if(cost[i][l]<cost[i][k])

near[i]=l;

else

near[i]=k;

near[k]=near[l]=-1;

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

int j=nearmin();

t[i][0]= j;

t[i][1]= near[j];

mincost = mincost + cost[j][near[j]];

near[j] = -1;

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

if(near[k]!= -1 && cost[k][near[k]] > cost[k][j] )

near[k]=j;

return mincost;

public int nearmin()

int jmin=Integer.MAX_VALUE;
int jvalue = -1;

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

if(near[i]!= -1 && cost[i][near[i]]<jmin)

jmin=cost[i][near[i]];

jvalue=i;

return jvalue;

public static void main(String[] args) {

Prims p = new Prims();

int mincostresult = p.primsalgo();

System.out.println("Minumum Cost: "+mincostresult);

for(int i=0;i<p.n-1;i++)

System.out.println(p.t[i][0] + "--" + p.t[i][1]);

}
OUTPUT:
Minimum Cost: 37

0--5

2--3

3--4

1--2

1--6

1--0
DIJKSTARS ALGORITHM CODE :
public class Dijkstra {

int dist[];

int S[];

int n;

int cost[][];

public Dijkstra() {

n = 6;

cost = new int[][]{

{0, 50, 45, 10, Integer.MAX_VALUE, Integer.MAX_VALUE},

{Integer.MAX_VALUE, 0, 10, 15, Integer.MAX_VALUE, Integer.MAX_VALUE},

{Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 15, Integer.MAX_VALUE, 0},

{20, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 15, Integer.MAX_VALUE},

{Integer.MAX_VALUE, 20, 35, Integer.MAX_VALUE, 0, Integer.MAX_VALUE},

{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3,


0},

};

dist = new int[n];

S = new int[n];

public void shortestPaths(int v) {

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


S[i] = 0;

dist[i] = cost[v][i];

S[v] = 1;

dist[v] = 0;

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

int u = minDist();

S[u] = 1;

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

if (cost[u][w] != 0 && cost[u][w] != Integer.MAX_VALUE && S[w] == 0) {

if (dist[w] > dist[u] + cost[u][w]) {

dist[w] = dist[u] + cost[u][w];

public int minDist() {

int min = Integer.MAX_VALUE;

int u = -1;

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

if (dist[i] < min && S[i] != 1) {


min = dist[i];

u = i;

return u;

public void displayDist() {

int count = 0;

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

System.out.print("Distance from vertex 0"+ " to " +count+" is "+dist[i] + "\t");

count++;

System.out.println("\n");

System.out.println();

public static void main(String args[]) {

Dijkstra d = new Dijkstra();

d.shortestPaths(0);

d.displayDist();

}
OUTPUT:

Distance from vertex 0 to 0 is 0

Distance from vertex 0 to 1 is 45

Distance from vertex 0 to 2 is 45

Distance from vertex 0 to 3 is 10

Distance from vertex 0 to 4 is 25

Distance from vertex 0 to 5 is 2147483647


ALL PAIRS SHORTEST PATH ALGORITHM CODE :

public class APSP {

int n;

int cost[][];

int A[][];

public APSP() {

n = 3;

cost = new int[][] {

{0, 4, 1},

{6, 0, 2},

{3, Integer.MAX_VALUE, 0}

};

A = new int[n][n];

public void AP() {

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

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

A[i][j] = cost[i][j];

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

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


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

A[i][j] = minValue(A[i][j], A[i][k] + A[k][j]);

public int minValue(int x, int y) {

if (x < y) {

return x;

} else {

return y;

public void displayA() {

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

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

System.out.print(A[i][j] + "\t");

System.out.println();

public static void main(String[] args) {

APSP apsp = new APSP();

apsp.AP();
apsp.displayA();

OUTPUT:

0 4 1
5 0 2
3 7 0
TRAVELLING SALES MAN PROBLEM ALGORITHM CODE :

import java.util.*;

public class TSPDynamicDemo {

int n;

int Adjmat[][];

int[] verticesSet;

public TSPDynamicDemo() {

n = 4;

Adjmat = new int[][]{

{0, 10, 15, 20},

{5, 0, 9, 10},

{6, 13, 0, 12},

{8, 8, 9, 0}

};

verticesSet = new int[n - 1];

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

verticesSet[i - 1] = i;

int tspdp() {

int mincost = Integer.MAX_VALUE;

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


List<List<Integer>> result1 = permute(verticesSet);

Iterator<List<Integer>> itri = result1.iterator();

while (itri.hasNext()) {

int cost = 0;

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

int ipath = 1;

List<Integer> o = itri.next();

Iterator<Integer> itrj = o.iterator();

while (itrj.hasNext()) {

path[ipath++] = itrj.next();

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

cost += Adjmat[path[i]][path[i + 1]];

if (cost < mincost) {

mincost = cost;

minpath = path;

System.out.println("Minimum Cost Tour: " + mincost);

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

System.out.print(minpath[i] + "-->");

System.out.print(minpath[n]);
System.out.println();

return mincost;

public static void main(String args[]) {

TSPDynamicDemo t = new TSPDynamicDemo();

int cost = t.tspdp();

List<List<Integer>> permute(int[] nums) {

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

permuteHelper(result, new ArrayList<>(), nums);

return result;

private void permuteHelper(List<List<Integer>> result, List<Integer> current, int[] nums) {

if (current.size() == nums.length) {

result.add(new ArrayList<>(current));

return;

for (int i = 0; i < nums.length; i++) {

if (current.contains(nums[i])) {

continue;

}
current.add(nums[i]);

permuteHelper(result, current, nums);

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

OUTPUT:

Minimum Cost Tour: 35

0-->1-->3-->2-->0
KNAPSACK 0/1 ALGORITHM CODE :

public class KnapsackDynamicDemo {

public void knapsack(int[] p, int[] w, int C, int[][] f) {

int n = p.length - 1;

int yMax = Math.min(w[n] - 1, C);

for (int y = 0; y <= yMax; y++)

f[n][y] = 0;

for (int y = w[n]; y <= C; y++)

f[n][y] = p[n];

for (int i = n - 1; i >= 1; i--) {

yMax = Math.min(w[i] - 1, C);

for (int y = 0; y <= yMax; y++)

f[i][y] = f[i + 1][y];

for (int y = w[i]; y <= C; y++)

f[i][y] = Math.max(f[i + 1][y], f[i + 1][y - w[i]] + p[i]);

f[1][C] = f[2][C];

if (C >= w[1])

f[1][C] = Math.max(f[1][C], f[2][C - w[1]] + p[1]);

public void traceback(int[][] f, int[] w, int C, int[] x) {

int n = w.length - 1;
for (int i = 1; i < n; i++)

if (f[i][C] == f[i + 1][C])

x[i] = 0;

else {

x[i] = 1;

C -= w[i];

x[n] = (f[n][C] > 0) ? 1 : 0;

public static void main(String[] args) {

KnapsackDynamicDemo k = new KnapsackDynamicDemo();

int n = 3;

int c = 6;

int[] p = {0, 1, 2, 5};

int[] w = {0, 2, 3, 4};

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

int[][] f = new int[n + 1][c + 1];

k.knapsack(p, w, c, f);

System.out.println("Optimal Profit: " + f[1][c]);

k.traceback(f, w, c, x);

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

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

System.out.println();
}

OUTPUT :
Optimal Profit: 61 0 1
N QUEENS PROBLEM ALGORITHM CODE :

public class NQueens {

int n;

int x[];

int solutions;

public NQueens() {

n = 4;

x = new int[n];

solutions = 0;

public void queens(int k, int n) {

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

if (place(k, i)) {

x[k] = i;

if (k == n - 1) {

display();

solutions++;

} else

queens(k + 1, n);

}
public boolean place(int k, int i) {

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

if (x[j] == i || Math.abs(x[j] - i) == Math.abs(j - k))

return false;

return true;

public void display() {

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

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

System.out.println();

public static void main(String[] args) {

NQueens q = new NQueens();

q.queens(0, 4);

System.out.println(q.solutions);

}
OUTPUT:
1302

2031

2
GRAPH COLOURING ALGORITHM CODE :

class GraphColoringDemo {

int n;

int m;

int cost[][];

int x[];

public GraphColoringDemo() {

n = 5;

cost = new int[][] {

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

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

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

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

{1, 1, 0, 1, 0}

};

m = 3;

x = new int[n];

public void mColoring(int k) {

do {
nextValue(k);

if (x[k] == 0)

return;

if (k == n - 1)

display();

else

mColoring(k + 1);

} while (true);

public void nextValue(int k) {

do {

int j = 0;

x[k] = (x[k] + 1) % (m + 1);

if (x[k] == 0)

return;

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

if ((cost[k][j] != 0) && (x[k] == x[j]))

break;

if (j == n)

return;

} while (true);

}
public void display() {

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

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

System.out.println();

public static void main(String[] args) {

GraphColoringDemo c = new GraphColoringDemo();

c.mColoring(0);

}
OUTPUT:

1 2 3 1 3

1 2 3 2 3

1 3 2 1 2

1 3 2 3 2

2 1 3 1 3

2 1 3 2 3

2 3 1 2 1

2 3 1 3 1

3 1 2 1 2

3 1 2 3 2

3 2 1 2 1

3 2 1 3 1
KRUSKALS ALGORITHM CODE :

import java.util.*;

public class KruskalDemo {

public class Edge {

public int u;

public int v;

public int w;

public Edge(int u, int v, int w) {

this.u = u;

this.v = v;

this.w = w;

public int getU() {

return u;

public int getV() {

return v;

public int getW() {


return w;

public class EdgeComparator implements Comparator<Edge> {

public int compare(Edge e1, Edge e2) {

if (e1.w > e2.w)

return 1;

else if (e1.w < e2.w)

return -1;

return 0;

PriorityQueue<Edge> minHeap;

public int n;

public int cost[][];

public int parent[];

public int mincost;

int t[][];

public KruskalDemo() {

n = 7;

cost = new int[][]{


{Integer.MAX_VALUE, 28, Integer.MAX_VALUE, Integer.MAX_VALUE,
Integer.MAX_VALUE, 10, Integer.MAX_VALUE},

{28, Integer.MAX_VALUE, 16, Integer.MAX_VALUE, Integer.MAX_VALUE,


Integer.MAX_VALUE, 14},

{Integer.MAX_VALUE, 16, Integer.MAX_VALUE, 12, Integer.MAX_VALUE,


Integer.MAX_VALUE, Integer.MAX_VALUE},

{Integer.MAX_VALUE, Integer.MAX_VALUE, 12, Integer.MAX_VALUE, 22,


Integer.MAX_VALUE, 18},

{Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 22,


Integer.MAX_VALUE, 25, 24},

{10, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 25,


Integer.MAX_VALUE, Integer.MAX_VALUE},

{Integer.MAX_VALUE, 14, Integer.MAX_VALUE, 18, 24, Integer.MAX_VALUE,


Integer.MAX_VALUE},

};

parent = new int[n];

t = new int[n][2];

minHeap = new PriorityQueue<>(new EdgeComparator());

public void CreateMinHeap() {

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

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

if (cost[i][j] != Integer.MAX_VALUE) {

Edge edge = new Edge(i, j, cost[i][j]);

minHeap.add(edge);

}
}

public int find(int i) {

if (parent[i] == -1)

return i;

return find(parent[i]);

public void union(int i, int j) {

parent[i] = j;

public void kruskalMST() {

CreateMinHeap();

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

parent[m] = -1;

int i = 0;

mincost = 0;

while (i < n - 1 && !minHeap.isEmpty()) {

Edge e = minHeap.poll();

int u = e.getU();

int v = e.getV();
int j = find(u);

int k = find(v);

if (j != k) {

i = i + 1;

t[i][0] = u;

t[i][1] = v;

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

union(j, k);

public static void main(String[] args) {

KruskalDemo k = new KruskalDemo();

k.kruskalMST();

System.out.println("Minimum Cost: " + k.mincost);

OUTPUT :
Minimum Cost: 99
HAMILTONIAN CYCLE ALGORITHM CODE :

public class Main {

int n;

int cost[][];

int x[];

public Main() {

n = 6;

cost = new int[][]{

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

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

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

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

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

};

x = new int[n];

x[0] = 1;

public void hamiltonian(int k) {

do {

nextValue(k);

if (x[k] == 0)
return;

if (k == n - 1)

display();

else

hamiltonian(k + 1);

} while (true);

public void nextValue(int k) {

do {

int j = 0;

x[k] = (x[k] + 1) % n;

if (x[k] == 0)

return;

if (cost[x[k - 1] - 1][x[k] - 1] != 0) {

for (j = 0; j < k; j++) {

if (x[j] == x[k])

break;

if (j == k && ((k < n - 1) || ((k == n - 1) && cost[x[n - 1] - 1][x[0] - 1] != 0)))

return;

} while (true);

}
public void display() {

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

System.out.print((x[i] - 1) + "\t");

System.out.print((x[0] - 1) + "\t");

System.out.println();

public static void main(String args[]) {

Main c = new Main();

c.hamiltonian(1);

OUTPUT :
011010
101001

110101
100101
010010

0 1 2 3 4 5 0

You might also like