3
\$\begingroup\$

Is there a way to speed up this code so it is \$O(n^2)\$ instead of \$O(n^3)\$? I'd appreciate if someone showed me how to do so.

public void minimalSpanning(int sVertex)
{
 source = sVertex;
 boolean[] mstv = new boolean[maxSize];
 for (int j = 0; j < gSize; j++)
 {
 mstv[j] = false;
 edges[j] = source;
 edgeWeights[j] = weights[source][j];
 }
 mstv[source] = true;
 edgeWeights[source] = 0;
 for (int i = 0; i < gSize - 1; i++)
 {
 double minWeight = Integer.MAX_VALUE;
 int startVertex = 0;
 int endVertex = 0;
 for (int j = 0; j < gSize; j++)
 if (mstv[j])
 for (int k = 0; k < gSize; k++)
 if (!mstv[k] && weights[j][k] < minWeight)
 {
 endVertex = k;
 startVertex = j;
 minWeight = weights[j][k];
 }
 mstv[endVertex] = true;
 edges[endVertex] = startVertex;
 edgeWeights[endVertex] = minWeight;
 } //end for
} //end minimalSpanning
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Jul 30, 2015 at 23:47
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Just some points:

  1. Naming:

    What does mstv mean? I assumed that ms in mstv stands for minimal spanning, but what is tv then? Television?

    Try clearing that up with a more "reasonable" name.

  2. Bad Practices:

    This is definitely prone to bugs:

     for (int j = 0; j < gSize; j++)
     if (mstv[j])
     for (int k = 0; k < gSize; k++)
     if (!mstv[k] && weights[j][k] < minWeight)
     {
     endVertex = k;
     startVertex = j;
     minWeight = weights[j][k];
     }
    

    Even though there might be no bugs in the code above, accidental mistakes do occur more if you lack braces.

    Instead, add the braces, which makes the code both more readable and less error-prone:

    for (int j = 0; j < gSize; j++) {
     if (mstv[j]) {
     for (int k = 0; k < gSize; k++) {
     if (!mstv[k] && weights[j][k] < minWeight) {
     endVertex = k;
     startVertex = j;
     minWeight = weights[j][k];
     }
     }
     }
    }
    

    (Note that this is using my coding habits; you may move the braces where you are comfortable with)

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Jul 31, 2015 at 16:10
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.