跳到主要内容位置

Time-Complexity-using-while-and-if

for i = 1 to n do step 2
{
stat;
}
while(condition)
{
stat;
}
do{
}while(condition)

do loop is Posteriori loop,executes statement first then executes condition while loop is prior loop,executes condition first then executes statement

repeat{
stat;
}until(condition)

repeat will always execute if the condition is false do will always execute if the condition is true

i = 0                     -> 1
while(i < n){ -> n + 1
stat; -> n
i ++ -> n
}

f(n)=3n+2O(n)=nf(n) = 3n + 2 \Rightarrow O(n) = n

for(i = 0; i < n; i++)          -> n + 1
{
stat; -> n
}

f(n)=2n+1O(n)=nf(n) = 2n + 1 \Rightarrow O(n) = n

a = 1
while(a < b)
{
stat
a = a * 2
}

aba=2k2kbk=log2bO(log2n)a \geq b \Rightarrow a = 2^k \Rightarrow 2^k \geq b \Rightarrow k = \log_2b \Rightarrow O(\log_2n)

i = n
while(i > 1)
{
stat;
i = i /2;
}

same as the previous one

O(log2n)O(\log_2n)