@@ -7,53 +7,31 @@ import DisjointSet from '../../../data-structures/disjoint-set/DisjointSet';
7
7
* @return {Graph }
8
8
*/
9
9
export default function kruskal ( graph ) {
10
- // It should fire error if graph is directed since the algorithm works only
11
- // for undirected graphs.
10
+ // Check for directed graph
12
11
if ( graph . isDirected ) {
13
- throw new Error ( ' Kruskal\ 's algorithms works only for undirected graphs' ) ;
12
+ throw new Error ( " Kruskal's algorithm works only for undirected graphs" ) ;
14
13
}
15
14
16
- // Init new graph that will contain minimum spanning tree of original graph.
15
+ // Initialize the MST graph
17
16
const minimumSpanningTree = new Graph ( ) ;
18
17
19
- // Sort all graph edges in increasing order.
20
- const sortingCallbacks = {
18
+ // Sort all edges by weight in ascending order
19
+ const sortedEdges = new QuickSort ( {
21
20
/**
22
21
* @param {GraphEdge } graphEdgeA
23
22
* @param {GraphEdge } graphEdgeB
24
23
*/
25
- compareCallback : ( graphEdgeA , graphEdgeB ) => {
26
- if ( graphEdgeA . weight === graphEdgeB . weight ) {
27
- return 1 ;
28
- }
24
+ compareCallback : ( graphEdgeA , graphEdgeB ) => graphEdgeA . weight - graphEdgeB . weight ,
25
+ } ) . sort ( graph . getAllEdges ( ) ) ;
29
26
30
- return graphEdgeA . weight <= graphEdgeB . weight ? - 1 : 1 ;
31
- } ,
32
- } ;
33
- const sortedEdges = new QuickSort ( sortingCallbacks ) . sort ( graph . getAllEdges ( ) ) ;
27
+ // Initialize disjoint sets for vertices
28
+ const disjointSet = new DisjointSet ( ( vertex ) => vertex . getKey ( ) ) ;
29
+ graph . getAllVertices ( ) . forEach ( ( vertex ) => disjointSet . makeSet ( vertex ) ) ;
34
30
35
- // Create disjoint sets for all graph vertices.
36
- const keyCallback = ( graphVertex ) => graphVertex . getKey ( ) ;
37
- const disjointSet = new DisjointSet ( keyCallback ) ;
38
-
39
- graph . getAllVertices ( ) . forEach ( ( graphVertex ) => {
40
- disjointSet . makeSet ( graphVertex ) ;
41
- } ) ;
42
-
43
- // Go through all edges started from the minimum one and try to add them
44
- // to minimum spanning tree. The criteria of adding the edge would be whether
45
- // it is forms the cycle or not (if it connects two vertices from one disjoint
46
- // set or not).
47
- for ( let edgeIndex = 0 ; edgeIndex < sortedEdges . length ; edgeIndex += 1 ) {
48
- /** @var {GraphEdge} currentEdge */
49
- const currentEdge = sortedEdges [ edgeIndex ] ;
50
-
51
- // Check if edge forms the cycle. If it does then skip it.
31
+ // Add edges to the MST if they don’t form a cycle
32
+ for ( const currentEdge of sortedEdges ) {
52
33
if ( ! disjointSet . inSameSet ( currentEdge . startVertex , currentEdge . endVertex ) ) {
53
- // Unite two subsets into one.
54
34
disjointSet . union ( currentEdge . startVertex , currentEdge . endVertex ) ;
55
-
56
- // Add this edge to spanning tree.
57
35
minimumSpanningTree . addEdge ( currentEdge ) ;
58
36
}
59
37
}
0 commit comments