Skip to content

Commit

Permalink
Merge pull request #325 from cunhazera/prim-java
Browse files Browse the repository at this point in the history
Adding prim in java
  • Loading branch information
Kanhakhatri065 authored Oct 6, 2020
2 parents 6974d11 + af6b20b commit 72d12a5
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Algorithms/Prim.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
public class Prim {

private int vertices = 5;

int minimum_key(int k[], int mst[]) {
int minimum = Integer.MAX_VALUE, min = 0, i;
for (i = 0; i < vertices; i++) {
if (mst[i] == 0 && k[i] < minimum) {
minimum = k[i];
min = i;
}
}
return min;
}

void prim(int[][] g) {
int[] parent = new int[vertices];
int[] k = new int[vertices];
int[] mst = new int[vertices];
int i, count, u, v;
for (i = 0; i < vertices; i++) {
k[i] = Integer.MAX_VALUE;
mst[i] = 0;
}

k[0] = 0;
parent[0] = -1;

for (count = 0; count < vertices - 1; count++) {
u = minimum_key(k, mst);
mst[u] = 1;
for (v = 0; v < vertices; v++)
if (g[u][v] != 0 && mst[v] == 0 && g[u][v] < k[v]) {
parent[v] = u;
k[v] = g[u][v];
}
}

for (i = 1; i < vertices; i++)
System.out.println(String.format("%d %d %d \n", parent[i], i, g[i][parent[i]]));
}


public static void main(String[] args) {
Prim instance = new Prim();
int[][] g = {{3, 2, 1, 9, 0}, {5, 1, 2, 10, 4}, {0, 4, 1, 0, 9}, {8, 10, 0, 2, 10}, {1, 6, 8, 11, 0}};
instance.prim(g);
}

}

0 comments on commit 72d12a5

Please sign in to comment.