Recitation 9/24/97 o Analyzing running time o Order notation o Getting a feel for running times of programs ------------------------------------------------------------------------- Let's do some more examples of figuring out the running time of programs. void foo(int A[], int n) { for(int i=0; i < n; ++i) { int min = i; for(int j=0; j < n; ++j) { if (j > i && A[j] < A[min]) min = j; } swap A[i] and A[j] } } (This is a slow sorting algorithm) Find running time: * First we initialize i to zero. * outer loop runs n times. On each run: - do a constant amount of work (set min=i. set j=0. etc.) - inner loop runs n times. On each run: do a constant amount of work - then do a constant amount of work to swap. So, running time T(n) = c1 + c2*n + c3*n^2, for some constants c1, c2, c3 > 0 Let's describe this using O(), Omega(), and Theta() notation. The basic idea is we toss out the low-order terms and ignore constants. So, we would say that this is Theta(n^2). More formally: Let f(n) be some function we're trying to compare our running time to. What we do is look at the limit of the ratio T(n)/f(n) as n goes to infinity: infinity --> CASE A lim T(n) / f(n) == number > 0 (e.g., 17) --> CASE B n->inf 0 --> CASE C CASE B or C: we say T(n) = O( f(n) ) - i.e., at most proportional CASE A or B: we say T(n) = Omega(f(n)) - i.e., at least proportional In the overlap (CASE B): T(n) = THETA( f(n) ). c3*n^2 + c2*n + c1 lim ------------------- n-->infinity n^2 By algebra this is c2 c1 lim c3 + --- + --- = c3 n-->infinity n n*n So, we're Theta(n^2). (Note that if the limit does not exist, e.g., T(n) = n sin n, then you need to go back to the full formal definition from lecture. E.g., in this case we would say T(n) = Theta(n).) [If students ask, you can say that "little-oh" is for CASE C only, and "little-omega" is for CASE A only, but we won't use these in this class] Another couple examples void f(int n) { for(int i=0; i < n; ++i) { .. some constant-time stuff.. } for(int i=0; i < n; ++i) { for(int j = i; j < n; ++j) { .. some constant-time stuff.. } for(int k=i; k < n; ++k) { .. some constant-time stuff.. } } } Answer: theta(n^2). void g(int n) { for(int i=0; i