Question

Can anyone help me analyze the run time of the following pseudocode

for(i = 0; i < n*n*n; i++)
    for(j = i; j < n; j++)
        x++

The way I see it's omega(n^3) for the lower bound, since that's what it would be if inside the outer for-loop was just theta(1).

I'm getting confused by the inner loop that only runs for the first n iterations of the outer loop. Do I just average the run-time of the inside loop: n^3 * ((1/n^2)*n + (1/n)*1, in which case it's O(n^3)?

Was it helpful?

Solution

Depends how smart your compiler is. The algorithms can be split into two parts (this may have off by one errors, but you get the idea)

// i<n
// O(n^2)
for( i=0; i<n ; ++i )
  for( j=i; j<n; ++j )
    x++

// n < i < n*n*n
// O(n^3)
for( i=n ; i<n*n*n; ++j)
  noop(); //do nothing

For i > n the second part does nothing, so a smart compiler will only loop i to n, in which case it is O(n^2).

However if your compiler isn't smart the latter half will execute too and you will just get an O(1) comparison and so overall behaviour is O(n^3).

OTHER TIPS

The inner loop will only get executed if i<n. So it is O(n^2).

Your algorithm should be dissected like the following:

for(i = 0; i < n*n*n; i++) {
    for(j = i; j < n; j++) {
        x++
    }
    if (i >= n) {
        y ++;
    }
}

Where x computes the number of both inner and outer loops, and y will reckon the number of iterations of the outer loop when the inner loop isn't to be executed anymore.

Therefore, you can formally proceed like the following:

enter image description here

When n = 10, the result will be: x = 55, and y = 990, which is compatible with the formula above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top