Destidom
Destidom

Reputation: 97

Analyse this Method

Im having a problem analyzing this method. Im trying to figure out the big Oh complexity. If I'm right it is O(n^2) hence the two for loops, which is the domninant joint of the algorithm. But i can't seem to figure out how to prove it.

The thing i got this far is.

1+n*((n-1)+1)/2+n. But when i test this it cant be right, can it?

Text is in norwegian, if you have any problem with understanding the code just yell out. (Should code in english but because our teachers is giving all the material in norwegian, they want it back in norwegian. Hence the english and norwegian text :P )

public void skrivUtStat(){
    LinearNode<CD> temp = start;
    int[] amt = new int[CD.GenreAmt()];
    String[] genre = CD.sendGenre();

    if(amount != 0){
        for(int i=0; i<amount; i++){
            for(int j=0; j<CD.genreAmount(); j++){
                if(temp.getElement().getGenreNr() == j){
                    ant[j] += 1;
                }
            } // End inner for-loop
            temp = temp.GetNext();                              // O(1)
        }// End outer for-loop

        for(int a=0; a<CD.GenreAmt(); a++){
            System.out.println(Genre[a] + ":");
            System.out.println(ant[a]);
        }
    }
}

Edited to english now.

Upvotes: 1

Views: 120

Answers (1)

helios
helios

Reputation: 13841

I understand that CD.genreAmount() is O(1) and you have a fixed list of genres. Right?

In that case you're iterating over all of your CD's (for i) and checking each one against your entire genre global listing (for j). So:

Being:

  • N = CD count
  • M = Genre count

Order will by O(N.M)

Of course: your algorithm is iterating over you genres again (at the end of method), but that's will be N.M + M, and of course O(M) is always lower than O(N.M)... so O(N.M+M) is equivalent to O(N.M)

Upvotes: 1

Related Questions