简体   繁体   English

算法的复杂度和Big-O

[英]Complexity and Big - O of an algorithm

So I am preparing for an exam and 25% of that exam is over Big-O and I'm kind of lost at how to get the complexity and Big-O from an algorithm. 因此,我正在为考试做准备,其中25%的考试超过了Big-O,而我对于如何从算法中获得复杂性和Big-O感到迷茫。 Below are examples with the answers, I just need an explanation of how to the answers came to be and reasoning as to why some things are done, this is the best explanation I can give because, as mentioned above, I don't know this very well: 以下是带有答案的示例,我只需要解释答案的产生方式以及做出某些事情的原因,这是我能给出的最佳解释,因为如上所述,我不知道这一点很好:

    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))

Number 4: the for loop counts from 1 to N, so it is at least O(n). 数字4: for循环从1到N计数,因此至少为O(n)。 The while loop takes O(log n) the first time, but since i doesn't get reset, while loop has only has one iteration each successive time through the for loop. while循环第一次使用O(log n),但是由于i没有被重置,因此while循环在for循环中每次连​​续只有一次迭代。 So basically O(n + log n), which simplifies to O(n). 因此基本上是O(n + log n),简化为O(n)。

Number 5: same as above, but now i does get reset each time, so you have O(log n) done N times: O(n log 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