Analyzing Algorithms
Prediction of resource use:
- time
- chip space
- memory
- communication resources
Model of Computation (implementation technology)
Random Access Machine
- memory accesses are all the same cost
- One instruction executed at a time
Terms
- Input Size -- Problem dependent, in sorting -- number of items, in multiplication -- number of bits.
- Ci = the cost of executing a line i
- times -- number of times a line is executed
Insertion-Sort(A) |
Cost |
Times |
1 for j ¬ 2 to length[A] |
C1 |
n |
2 do key ¬ A[j] |
C2 |
n -1 |
3 Insert A[j] into the sorted sequence A[1..j-1]. |
0 |
n - 1 |
4 i ¬ j - 1 |
C4 |
n - 1 |
5 while i > 0 and A[i] > key |
C5 |
|
6 do A[i + 1] ¬ A[i] |
C6 |
|
7 i ¬ i - 1 |
C7 |
|
8 A[i + 1] ¬ key |
C8 |
n - 1 |
tj = the number of times line 5 is executed, or how long you search for your spot
T (n) = |
C1 n + C2 (n-1) + C4 (n-1) + |
n
C5å tj +
j = 2 |
n
C6å (tj - 1) +
j = 2 |
n
C7å (tj - 1) + C8(n-1)
j = 2 |
Best case ( tj = 1) no search required, list is already sorted.
T (n) = ( C1 + C2 + C4 + C5 + C8 )n - ( C2 + C4 + C5 + C8 )
= a
n + b
T (n) is a linear function of n
Worst case analysis:
Input is "all wrong": a1 ³ a2 ³ a3 ³ ... an means that tj
= j ( we must compare all the elemnts each time!)
T (n) = ( C5 / 2 + C6 / 2 + C7 / 2 ) n 2 + n( C1 + C2 + C4 + C5 / 2 - C6 / 2 - C7 / 2 + C8 ) - ( C2 + C4
+ C5 + C8 )
= a n2 + b n + c -- a quadratic function of n
Why use a worst case analysis
- Upper bound for all cases
- Worst case "may" be a typical case
- Average case may be approximately the worst case (( tj = j / 2 ) is roughly quadratic.)
- Often it is hard to pick average cases and compute expected times.
Rate of Growth of Functions
a n2 + b n + c or O (n2 ) is an order of growth.
|