Komplexität Algorithmus

Maultäschle

Aktives Mitglied
Hey🙂

Ich hab diesen Algorithmus bekommen und soll davon die Komplexität angeben, leider bin ich mir nicht so sicher, deshalb wäre ich froh zu hören, was ihr so habt🙂
Java:
public void alg2(int n) {
  int result = 1;
  while (result < n) {
    if (result >= n / 2) {
      result = n;
    } else {
      result = result * 2;
    }
  }
}
 
Zuletzt bearbeitet von einem Moderator:
Deine Vermutung bestätigt sich:
Java:
    public static void main(String[] args) {
        System.out.println("alg2   Llog(n)L");
        for (int i = 0; i < 100_000; i++) {
            System.out.println(alg2(i) + "   " + Math.round(Math.log(i) / Math.log(2)));
        }
    }

    public static int alg2(int n) {
        int r = 0;
        int result = 1;
        while (result < n) {
            if (result >= n / 2) {
                result = n;
            } else {
                result = result * 2;
            }
            r++;
        }
        return r;
    }

Exakt geht's leider nicht, da Funktion etwas springt.
 
strike, es geht doch exakt, aber das ist schon nicht mehr so toll:
Java:
    public static void main(String[] args) {
        System.out.println("alg2   Llog(n)L");
        for (int i = 3; i < 100_000; i++) {
            double d = Math.ceil(Math.log(i - Double.longBitsToDouble(Double.doubleToLongBits(1) - 1)) / Math.log(2));
            System.out.println(alg2(i) + "   " + d);
        }
    }

    public static int alg2(int n) {
        int r = 0;
        int result = 1;
        while (result < n) {
            if (result >= n / 2) {
                result = n;
            } else {
                result = result * 2;
            }
            r++;
        }
        return r;
    }

Alles baut auf Math.log() auf. Also an deiner Antwort ändert das nix, diese ist richtig.
 
Hey🙂
Und noch zu diesem Algorithmus. Ich hab da n*log(n). Passt des?
Code:
public int alg5(int n) { 2 if (n == 0) {
}
int i= 1;
intj= n;
while(i<j){
i=i+ 1;
j=j- 1;
}

return alg5(i - 1)+1; 14
}
 
Formatier doch bitte richtig. 😉
14?
Auf den ersten Blick ist das nicht zu erkennen.
Rekursion ist im Spiel.
Deswegen nimm das Mastertheorem.
 
Moin, n wäre richtig, wenn ich das richtig aufgefasst habe. Hier die Bestätigung:
Java:
    static int k = 0;

    public static void main(String[] args) {
        System.out.println("alg5   LnL");
        for (int i = 3; i < 100000; i++) {
            System.out.println(alg5(i) + "  " + k + "  " + ((i / 2 + i / 2) / 2 * 2));
            k = 0;
        }
    }

    static int alg5(int n) {
        if (n == 0) {
            return 0;
        }
        int i = 1;
        int j = n;
        while (i < j) {
            i = i + 1;
            j = j - 1;
            k++;
        }
        return alg5(i - 1) + 1;
    }

Mastertheorem: 1*T(n/2)+n , wäre das. Ich weiß aber nicht, welcher case. 🙁

Sorry, für das, was ich gestern verzapft habe!
 

Zurück
Oben