File tree Expand file tree Collapse file tree 4 files changed +76
-1
lines changed Expand file tree Collapse file tree 4 files changed +76
-1
lines changed Original file line number Diff line number Diff line change 1313 "mst" : {
1414 "name" : " Minimum Spanning Tree" ,
1515 "list" : {
16- "prim" : " Prim's Algorithm"
16+ "prim" : " Prim's Algorithm" ,
17+ "kruskal" : " Kruskal's Algorithm"
1718 }
1819 },
1920 "search" : {
Original file line number Diff line number Diff line change 1+ {
2+ "Kruskal's Algorithm" : " Greedy algorithm that finds a minimum spanning tree for a weighted undirected graph." ,
3+ "Applications" : [
4+ ],
5+ "Complexity" : {
6+ "time" : " worst O(E log(E))"
7+ },
8+ "References" : [
9+ " <a href='https://en.wikipedia.org/wiki/Kruskal%27s_algorithm'>Wikipedia</a>"
10+ ],
11+ "files" : {
12+ "normal" : " Finds minimum spanning tree of a given graph."
13+ }
14+ }
Original file line number Diff line number Diff line change 1+ function kruskal ( ) {
2+ var vcount = G . length ;
3+
4+ // Preprocess: sort edges by weight.
5+ var edges = [ ] ;
6+ for ( var vi = 0 ; vi < vcount - 1 ; vi ++ ) {
7+ for ( var vj = vi + 1 ; vj < vcount ; vj ++ ) {
8+ edges . push ( {
9+ 0 : vi ,
10+ 1 : vj ,
11+ weight : G [ vi ] [ vj ]
12+ } ) ;
13+ }
14+ }
15+ edges . sort ( function ( ei , ej ) { return ei . weight - ej . weight } ) ;
16+
17+ // Give each vertex a tree to decide if they are already in the same tree.
18+ var t = [ ] ;
19+ for ( var i = 0 ; i < vcount ; i ++ ) {
20+ t [ i ] = { } ;
21+ t [ i ] [ i ] = true ;
22+ }
23+
24+ var wsum = 0 ;
25+ for ( var n = 0 ; n < vcount - 1 && edges . length > 0 ; ) {
26+ var e = edges . shift ( ) ; // Get the edge of min weight
27+ tracer . _visit ( e [ 0 ] , e [ 1 ] ) ;
28+ if ( t [ e [ 0 ] ] === t [ e [ 1 ] ] ) {
29+ // e[0] & e[1] already in the same tree, ignore
30+ tracer . _leave ( e [ 0 ] , e [ 1 ] ) ;
31+ continue ;
32+ }
33+
34+ // Choose the current edge.
35+ wsum += e . weight ;
36+
37+ // Merge tree of e[0] & e[1]
38+ var tmerged = { } ;
39+ for ( i in t [ e [ 0 ] ] ) tmerged [ i ] = true ;
40+ for ( i in t [ e [ 1 ] ] ) tmerged [ i ] = true ;
41+ for ( i in tmerged ) t [ i ] = tmerged ;
42+
43+ n += 1 ;
44+ }
45+
46+ tracer . _print ( "The sum of all edges is: " + wsum ) ;
47+ }
48+
49+ tracer . _pace ( 500 ) ;
50+ kruskal ( ) ;
Original file line number Diff line number Diff line change 1+ var tracer = new WeightedUndirectedGraphTracer ( ) ;
2+ /*var G = [ // G[i][j] indicates the weight of the path from the i-th node to the j-th node
3+ [0, 3, 0, 1, 0],
4+ [5, 0, 1, 2, 4],
5+ [1, 0, 0, 2, 0],
6+ [0, 2, 0, 0, 1],
7+ [0, 1, 3, 0, 0]
8+ ];*/
9+ var G = WeightedUndirectedGraph . random ( 5 , 1 , 1 , 9 ) ;
10+ tracer . _setData ( G ) ;
You can’t perform that action at this time.
0 commit comments