Your friend is comparing two different values of n rather than comparing the same value. That is, g is an upper bound for f if, for the same value of n g(n) ≥ f(n).
int i = 2; int * ip = &i; /* point 1 */ i = 3; /* point 2 */ *ip = 8; /* point 3 */
Be sure to show all your steps and state your assumptions.int find(int a[], int n, int x) for (i = 0; i < n; i++) if a[i] == x return i return -1
Starting with individual statements:
The if statement's next:int find(int a[], int n, int x) for (i = 0; i < n; i++) if a[i] == x O(1) O(1)
The array access takes constant time, as does the comparison. The for loop is equivalent to a while loop with some overhead.int find(int a[], int n, int x) for (i = 0; i < n; i++) O(1) + O(min(1, 1) = O(1) + O(1) = O(1) O(1)
Prefix increment takes constant time, as does the assignment to i.int find(int a[], int n, int x) i = 0 while i < n O(1) i++ O(1)
The sequence of two constant-time statements is again a constant time statement.int find(int a[], int n, int x) O(i) while i < n O(1) O(1) O(1)
The number of interations is bounded byint find(int a[], int n, int x) O(1) while i < n O(1) + O(1) = O(max(1, 1)) = O(1) O(1)
n
and the comparison takes
constant time.
Combining the remaining statement sequence gives the final answerint find(int a[], int n, int x) O(1) O(n)*(O(1) + O(1) = O(n)*O(1) = O(n*1) = O(n) O(1)
int find(int a[], int n, int x) O(1) + O(n) + O(1) = O(1) + O(max(n, 1)) = O(1) + O(n) = O(n)
a ? ( a ? a )
regular
expression.
All the strings start with a
. The first option may contribute a futher a
followed by an optional a
or not.
The final option may contribute ana a a ? a
a
or not.
a a a a a a
This page last modified on 7 February 2006.