Analysis of an Algorithm |
Document last modified: |
Assignment
| Find_Largest (A) //@ pre A != null; //@ post (\forall int i; 1 <= i && i <= A.length; A[\result] >= A[i]); // post: result = index in A of the largest element in A
|
Cost |
Times Executed |
|
| 1 | location ← 1 | c1 | 1 |
| 2 | for i ← 2 to length[A] do | c2 | n |
| 3 | if A[location] < A[i] then | c3 | n - 1 |
| 4 | location ← i | c4 | n - 1 |
| 5 | return location | c5 | 1 |
T(n) = c1 + c2n + c3(n - 1) + c4(n - 1) + c5
= c1 + n(c2+c3+c4)
- (c3+c4) + c5
= n(c2+c3+c4)
+ c1 + c5 - (c3+c4)
= an + b
for some constants a and b.
The best case? Data that never executes line 4, when sorted in
descending order.
No. O(n) = T(n) = an + b
The loop invariant is:
/*@ loop_invariant (\forall int j;
1<=j && j < i && 1 <= location && location < i;
A[j] <= A[location]);
@*/
which says that for any value of j between 1 and length[A] (inclusive), that A[location] is greater than or equal to A[j], and so 'location' holds the index to a value in A that is at least as large as any other value in A.
Find_Largest (A) 1 location ← 1 2 -- "j: 1 ≤ j < i, 1 ≤ location < i, A[j] ≤ A[location] for i ← 2 to length[A] do
3 if A[location] < A[i] then 4 location ← i 5 return location