 21

n

S
n

n

s
i

t
()

t
(
s
i
)

s
i
S
n

S
n

T
wc
(
n
)
T
wc
(
n
)

s
i

2.3.2 平均情况

n

n

n/
2

n/
2

n/
2

n/
2

n

Pr
{
s
i
}

0
1
，所有样本的概率的和为
1
。更加正式一点的定义为，如果
S
n

n

s
S
Pr s
i
=1

t
()

S
n

exceedingly small. Instead, we could design a system that is cheaper to build and use
mathematical tools to consider the probability of crash due to overload.
For the set of instances of size n, we associate a probability distribution Pr{s
i
}, which
assigns a probability between 0 and 1 to each instance s
i
such that the sum of the
probabilities over all instances of size n is 1. More formally, if S
n
is the set of instan
ces of size n, then:
s
i
S
n
Pr s
i
=1
If t() measures the work done by an algorithm on each instance, then the average-
case work done by an algorithm on S
n
is:
T
ac
n =
s
i
S
n
t s
i
Pr s
i
That is, the actual work done on instance s
i
, t(s
i
), is weighted with the probability
that s
i
will actually be presented as input. If Pr{s
i
} = 0, then the actual value of t(s
i
)
does not impact the expected work done by the program. Denoting this average-
case work on S
n
by T
ac
(n), then the rate of growth of T
ac
(n) defines the average-case
complexity of the algorithm.
Recall that when describing the rate of growth of work or time, we consistently
ignore constants. So when we say that Sequential Search of n elements takes,
on average:
1
2
n +
1
2
probes (subject to our earlier assumptions), then by convention we simply say that
subject to these assumptions, we expect Sequential Search will examine a linear
number of elements, or order n.
Best Case
Knowing the best case for an algorithm is useful even though the situation rarely
occurs in practice. In many cases, it provides insight into the optimal circumstance
for an algorithm. For example, the best case for Sequential Search is when it
searches for a desired value, v, which ends up being the first element in the list.
Consider a slightly different approach, which well call Counting Search, that
counts the number of times that v appears in a list. If the computed count is zero,
then the item was not found, so it returns
false; otherwise, it returns true. Note
that Counting Search always searches through the entire list; therefore, even
though its worst-case behavior is O(n)—the same as Sequential Search—its best-
Mathematics
of
Algorithms
Analysis in the Best, Average, and Worst Cases | 17

s
i

t
(
s
i
)

Pr
{
s
i
}=0
，那么
t
(
s
i
)

T
ac
(
n
)

S
n

T
ac
(
n
)

n

Get 算法技术手册（原书第2 版） now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.