The running time of a for loop is at most the running time of the statements inside the for loop (including tests) times the number of iterations.
for (int i=1; i<=n; i++)
suma += array[i];
array[i] = array[i] * 2;
Question: What would be the running time in the Big-O notation?
The total running time of a statement inside a group of nested loops is the running time of the statement multiplied by the product of the sizes of all the loops. Let's try below:
// Example 1
for( i = 0; i < n; ++i )
for( j = 0; j < n; ++j )
++k;
// Example 2
for( i = 0; i < n; ++i )
for( j = 0; j < n; ++j ) {
++k;
array[i] = k*2;
}
These just add (which means that the maximum is the one that counts).
for( i = 0; i < n; ++i )
a[ i ] = 0;
for( i = 0; i < n; ++i )
for( j = 0; j < n; ++j )
a[ i ] += a[ j ] + i + j;
Question: And ... What would be the running time for this?
And ... what about the matrix multiplication algorithm?
for (int i=1; i<=n; i++)
for (int j=1; j<=n; j++) {
C[i,j] = 0;
for (int k=1; k<=n; k++)
C[i,j] = C[i,j] + A[i,k]*B[k,j];
}
Question, what's the running time?
if
/ else
long factorial( int n ) {
if( n <= 1 )
return 1; // S1
else
return n * factorial( n - 1 ); // S2
}
The running time of an if/else
statement is never more than the running time of the test plus the larger of the running times of S1 and S2.
So, from the example above, What would be the running time?
The running time is caculated by the number of recursive calls.
Common cases:
ant = 1;
act = 1;
while (n>2) {
aux = ant + act; ant = act;
act = aux;
n = n - 1;
}
printf("%d",act);
Question: What would be running time?
int fibonacci(int n) {
if (n < 3)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
Question: What would be running time?
iterative_fibonacci
and recursive_fibonacci
main
functions to support the following execution modes:
./main --iterative <n_start> <n_end>
./main --recursive <n_start> <n_end>
n
iteration and print it; and later graph it with your favorite graphics toolThis material is genereated thanks to some extracts from following resources:
AI Overview