Following is my pseudocode for converting a connected graph to MST using Prim's algorithm. I am however getting a complexity of n^3 rather then n^2. Please help me figure out the non-required steps.I have an adjacency matrix "a" to store the weight of graph edges and a 2D matrix "check" storing "1" for vertices already in the tree and "0" for remaining.
Please also note that this can be done in nlog(n) also, but I don't want to refer any existing pseudocode and want to try it on my own. I would appreciate an answer optimizing my own approach.
Initialize check. //check[0][1]==1
while(--no_of_vertices)
{
minimum_outer = infinite
for(i from 1 to no_of_vertices)
{
minimum_inner = infinite
select i from check having value 1
for(j from 1 to no_of_vertices )
{
select j from check having value 0
if(a[i-j] < minimum_inner)
minimum_inner = a[i-j]
temp_j = j;
}
if(minimum_inner<minimum_outer)
{
minimum_outer = minimum_inner
final_i = i
final_j = temp_j
}
}
//until here basically what I have done is, selected an i-j with lowest
//weight where "i" is chosen from vertices already in MST and "j" from
//remaining vertices
check[final_j][1] = 1
print final_i - final_j
cost_of_mst += a[final_i][final_j]
}