簡體   English   中英

算法的復雜度和Big-O

[英]Complexity and Big - O of an algorithm

因此,我正在為考試做准備,其中25%的考試超過了Big-O,而我對於如何從算法中獲得復雜性和Big-O感到迷茫。 以下是帶有答案的示例,我只需要解釋答案的產生方式以及做出某些事情的原因,這是我能給出的最佳解釋,因為如上所述,我不知道這一點很好:

    int i =n;  //this is 1 because it is an assignment (=)
    while (i>0){                //this is log10(10)*(1 or 2) because while 
        i/=10;  //2 bc / and = // loops are log base (whatever is being /='d
    } //the answer to this one is 1+log10(n)*(1 or 2) or O(logn)
      //so i know how to do this one, but im confused when while and for 
      //loops nested in each other

    int i = n; int s = 0;
    while (i>0){
        for(j=1;j<=i;j++)s++;{
        i/=2;
    } //the answer to this one is 2n +log2(n) + 2 or O(n)
      //also the i/=2 is outside for loop for this and the next one

    int i = n; int s=0
    while (i>0){
        for(j=1;j<=n;++J) s++;
        i/=2;
    } //answer 1+nlogn or O(nlogn)

    int i = n;
        for(j=1;j<=n;j++)
        while(i>o) i/=2; 
           //answer is 1+log2(n) or O(log(n))


    for(j=1; <=n; ++j){
        int i-n;
        while(i>0) i/=2;
    } //answer O(nlog(n))

數字4: for循環從1到N計數,因此至少為O(n)。 while循環第一次使用O(log n),但是由於i沒有被重置,因此while循環在for循環中每次連​​續只有一次迭代。 因此基本上是O(n + log n),簡化為O(n)。

5號:同上,但現在i 沒有得到重置每次,讓你有O(log n)的做過N次:為O(n log n)的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM