Determining the time complexities of worst case algorithms
Do the two algorithms have the same theta characterization of Θ(n^2)?
int sum = 0;
for (int i = 0; i < n; i++ )
for (int j = 0; j < n * n; j++ )
sum++;
int sum = 0;
for ( int i =开发者_如何学Go 0; i < n; i++)
for ( int j = 0; j < i; j++)
sum++;
If not then does this mean that this characterization is not Θ(n^3)?
int sum = 0;
for ( int i = 0; i < n; i++)
for ( int j = 0; j < i * i; j++ )
for ( int k = 0; k < j; k++ )
sum++;
@Dan, For the first one did you really mean j < n * n
rather than j < n
? If so, the time complexity of the first one is Θ(n^3), isn't it?
If you meant j < n
, then I believe the first two are both Θ(n^2): The first one takes n^2 steps, and the second one takes 1 + 2 + ... + n = n(n+1)/2 which is Θ(n^2).
I'm thinking the 3rd one is Θ(n^4), but it's harder to prove. Definitely O(n^4).
精彩评论