Include minimum weight edges one by one
var edge_count = 0 ; while ( edge_count < V - 1 ) { var min = INF , a = - 1 , b = - 1 ; for ( var i = 0 ; i < V ; i ++ ) { for ( var j = 0 ; j < V ; j ++ ) { if ( find ( i ) != find ( j ) && cost [ i ] [ j ] < min ) { min = cost [ i ] [ j ] ; a = i ; b = j ; } } } union1 ( a , b ) ; document . write ( ` ${ edge_count ++ } ${ a } ${ b } ${ min } ` ) ; mincost += min ; } document . write ( ` ${ mincost } ` ) ; }