5.5 Amortized CostThe Consider the problem in which a sequence of append operations are performed on an initially empty list, where is a power of . L = list() for i in range(1, n+1) : L.append(i) Suppose the array is doubled in capacity each time it has to be expanded and assume the size of the underlying array for an empty list has the capacity for a single item. We can tally or compute the total running time for this problem by considering the time required for each individual append operation. This approach is known as the aggregate method since it computes the total from the individual operations. Figure 5.5.1 illustrates the aggregate method when applied to a sequence of append operations. represents the time required to physically store the value when there is an available slot in the array or immediately after the array has been expanded. Storing an item into an array element is a constant time operation. represents the time required to expand the array when it does not contain available capacity to store the item. Based on our assumptions related to the size of the array, an expansion only occurs when is a power of and the time incurred is based on the current size of the array (). While every append operation entails a storage cost, relatively few require an expansion cost. Note that as the size of increases, the distance between append operations requiring an expansion also increases. Based on the tabulated results in Figure 5.5.1, the total time required to perform a sequence of append operations on an initially empty list is , or just under . This results from a total storage cost () of and a total expansion cost () of . It can be shown that for any , the sum of the storage and expansion costs, , will never be more than . Since there are relatively few expansion operations, the expansion cost can be distributed across the sequence of operations, resulting in an amortized cost of or for the append operation.
Amortized analysis is the process of computing the time-complexity for a sequence of operations by computing the average cost over the entire sequence. For this technique to be applied, the cost per operation must be known and it must vary in which many of the operations in the sequence contribute little cost and only a few operations contribute a high cost to the overall time. This is exactly the case with the
|