Is it possible for an algorithm/program to have the same worst-case and best-case time?
For example:
public static int factorial(int number)
{
factorial = 1;
for (i = 1; i <= number; i++)
factorial = factorial * i;
}
It’s a program segment for the factorial problem, and I was trying to solve for the time complexity. It seems to have no worst and best case time, since whatever input you may have it will still go through the rest of the code, unlike when you have if-else statements.
If that’s the case should I assume that what ever I get from this code it would be the best, worst and average case time?
Did I get this right?
public static int factorial(int number)
{
factorial = 1; // 1
for (i = 1; i <= number; i++) // 1+3n
factorial = factorial * i; // 2
return factorial; // 1
}
Worst Case/Best Case:
3n+5
Big – O :
O(n)
In your case when
"number"is fixed, your program has no worst or best case – it always does"number"iterations, so it has a linear complexity.For formal mathematical definitions see these articles:
http://en.wikipedia.org/wiki/Analysis_of_algorithms
http://en.wikipedia.org/wiki/Big_O_notation