Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 24c5194

Browse files
Create Kruskal’s_Algorithm.js
I want to contribute Kruskal’s Algorithm Simple Implementation for Adjacency Matrix
1 parent 9a87526 commit 24c5194

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Kruskal’s_Algorithm.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
var V = 5;
2+
var parent = Array(V).fill(0);
3+
var INF = 1000000000;
4+
5+
// Find set of vertex i
6+
function find(i)
7+
{
8+
while (parent[i] != i)
9+
i = parent[i];
10+
return i;
11+
}
12+
13+
// Does union of i and j. It returns
14+
// false if i and j are already in same
15+
// set.
16+
function union1(i, j)
17+
{
18+
var a = find(i);
19+
var b = find(j);
20+
parent[a] = b;
21+
}
22+
23+
// Finds MST using Kruskal's algorithm
24+
function kruskalMST(cost)
25+
{
26+
var mincost = 0; // Cost of min MST.
27+
28+
// Initialize sets of disjoint sets.
29+
for (var i = 0; i < V; i++)
30+
parent[i] = i;
31+
32+
// Include minimum weight edges one by one
33+
var edge_count = 0;
34+
while (edge_count < V - 1)
35+
{
36+
var min = INF, a = -1, b = -1;
37+
for (var i = 0; i < V; i++)
38+
{
39+
for (var j = 0; j < V; j++)
40+
{
41+
if (find(i) != find(j) && cost[i][j] < min)
42+
{
43+
min = cost[i][j];
44+
a = i;
45+
b = j;
46+
}
47+
}
48+
}
49+
50+
union1(a, b);
51+
document.write(`Edge ${edge_count++}:(${a},
52+
${b}) cost:${min} <br>`);
53+
mincost += min;
54+
}
55+
document.write(`<br> Minimum cost= ${mincost} <br>`);
56+
}
57+
58+
// Driver code
59+
60+
/* Let us create the following graph
61+
2 3
62+
(0)--(1)--(2)
63+
| / \ |
64+
6| 8/ \5 |7
65+
| / \ |
66+
(3)-------(4)
67+
9 */
68+
var cost = [
69+
[INF, 2, INF, 6, INF],
70+
[2, INF, 3, 8, 5],
71+
[INF, 3, INF, INF, 7],
72+
[6, 8, INF, INF, 9],
73+
[INF, 5, 7, 9, INF]];
74+
// Print the solution
75+
kruskalMST(cost);
76+

0 commit comments

Comments
 (0)