Include minimum weight edges one by one
int edge_count = 0 ; while ( edge_count < V - 1 ) { int min = INF , a = - 1 , b = - 1 ; for ( int i = 0 ; i < V ; i ++ ) { for ( int 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 ) ; System . out . printf ( "Edge %d:(%d, %d) cost:%d NEW_LINE", edge_count++, a, b, min); mincost += min ; } System . out . printf ( " Minimum cost = % d ", mincost); }