2 - Algorithm Analysis
2 - Algorithm Analysis
i i
i i
i i
If an algorithm has been implemented, we can study its running time by executing
it on various test inputs and recording the actual time spent in each execution. For-
tunately, such measurements can be taken in an accurate manner by using system
calls that are built into the language or operating system (for example, by using the
clock() function or calling the run-time environment with profiling enabled). Such
tests assign a specific running time to a specific input size, but we are interested in
determining the general dependence of running time on the size of the input. In or-
der to determine this dependence, we should perform several experiments on many
different test inputs of various sizes. Then we can visualize the results of such
experiments by plotting the performance of each run of the algorithm as a point
with x-coordinate equal to the input size, n, and y-coordinate equal to the running
time, t. (See Figure 4.3.) From this visualization and the data that supports it, we
can perform a statistical analysis that seeks to fit the best function of the input size
to the experimental data. To be meaningful, this analysis requires that we choose
good sample inputs and test enough of them to be able to make sound statistical
claims about the algorithm’s running time.
t (ms)
60
50
40
30
20
10
n
0 50 100
i i
i i
i i
i i
i i
i i
An algorithm may run faster on some inputs than it does on others of the same
size. Thus, we may wish to express the running time of an algorithm as the function
of the input size obtained by taking the average over all possible inputs of the same
size. Unfortunately, such an average-case analysis is typically quite challenging.
It requires us to define a probability distribution on the set of inputs, which is often
a difficult task. Figure 4.4 schematically shows how, depending on the input distri-
bution, the running time of an algorithm can be anywhere between the worst-case
time and the best-case time. For example, what if inputs are really only of types
“A” or “D”?
5 ms worst-case time
4 ms
} average-case time?
Running Time
3 ms
best-case time
2 ms
1 ms
A B C D E F G
Input Instance
Figure 4.4: The difference between best-case and worst-case time. Each bar repre-
sents the running time of some algorithm on a different possible input.
i i
i i
i i
i i
i i