Beruflich Dokumente
Kultur Dokumente
− + = − − + = + − .
2 i 2 4 2 i 2 4 4 i
i=2 i=2 i=1
Since
X
n
1
ln(n + 1) ≤ ≤ ln n + 1 (Eq. 2.16, page 80),
i
i=1
n2 3n
+ − ln n = Θ(n2 ).
4 4
Thus, on the average, Algorithm insertionsort performs roughly half the num-
ber of operations performed in the worst case (see Fig. 1.6).
Example 1.32 Consider the following problem. We have a doubly linked list
(see Sec. 3.2) that initially consists of one node which contains the integer 0. We
have as input an array A[1..n] of n positive integers that are to be processed in
the following way. If the current integer x is odd, then append x to the list. If
it is even, then first append x and then remove all odd elements before x in the
list. A sketch of an algorithm for this problem is shown below and is illustrated
in Fig. 1.7 on the input
5 7 3 4 9 8 7 3 .
1. for j ← 1 to n
2. x ← A[j]
3. append x to the list
4. if x is even then
5. while pred (x) is odd
6. delete pred (x)
7. end while
8. end if
9. end for
of iterations of the while loop is n − 1. This means that the while loop may
cost Ω(n) time in some iterations. It follows that each iteration of the for loop
takes O(n) time, which results in an overall running time of O(n2 ).
Using amortization, however, we obtain a time complexity of Θ(n) as follows.
The number of insertions is obviously n. As to the number of deletions, we note
that no element is deleted more than once, and thus the number of deletions is
between 0 and n − 1. It follows that the total number of elementary operations
of insertions and deletions altogether is between n and 2n − 1. This implies that
the time complexity of the algorithm is indeed Θ(n). It should be emphasized,
however, that in this case we say that the while loop takes constant amortized
time in the worst case. That is, the average time taken by the while loop is
guaranteed to be O(1) regardless of the input.
X
k
Thus, using amortization, it follows that the time needed to store and move each
of the elements x1 , x2 , . . . , xn is Θ(1) amortized time.