Growing Arrays 2004 Goodrich Tamassia Vectors 1 Problem
Growing Arrays © 2004 Goodrich, Tamassia Vectors 1
Problem with fixed-size Arrays In the implementation of stack or queue with an array, we had to set the array size to some initial capacity If the number of pushes (for a stack) or enqueues (for a queue) passes this capacity, we had to throw an exception Linked List implementation does not have this problem, but sometimes Linked List is not the best implementation Can we avoid the capacity limit in the arraybased implementations? © 2004 Goodrich, Tamassia Vectors 2
Growable Array Implementations (of stack, queue, array list, etc…) In a push (enqueue, etc) operation, when the array is full, instead of throwing an exception, we can replace the array with a larger one How large should the new array be? incremental strategy: increase the size by a constant c n doubling strategy: double the size Vectors © 2004 Goodrich, Tamassia n Algorithm push(o) if t = S. length 1 then A new array of size … for i 0 to t do A[i] S[i] S A t t+1 S[t] o 3
Comparison of the Strategies We compare the incremental strategy and the doubling strategy by analyzing the total time T(n) needed to perform a series of n push operations We assume that we start with an empty stack represented by an array of size 1 We call amortized time of a push operation the average time taken by a push over the series of operations, i. e. , T(n)/n © 2004 Goodrich, Tamassia Vectors 4
Incremental Strategy Analysis We replace the array k = n/c times The total cost T(n) of a series of n push operations is proportional to n + 2(c + 2 c + 3 c + 4 c + … + kc) = n + 2 c(1 + 2 + 3 + … + k) = n + 2 c × k(k + 1)/2 = O(n+k 2) Since c is a constant, T(n) = O(n+k 2) = O(n+(n/c)2) = O(n 2) The amortized time of 1 push is O(n 2)/n = O(n) © 2004 Goodrich, Tamassia Vectors 5
Doubling Strategy Analysis We replace the array k = log 2 n times geometric series The total time T(n) of a series of 2 n push operations is 4 proportional to 1 1 n + 2×(1 + 2 + 4 + 8 + …+ 2 k) = n + 2×(2 k + 1 1) = 3 n 2 = O(n) 8 The amortized time of 1 push is O(n)/n = O(1) © 2004 Goodrich, Tamassia Vectors 6
- Slides: 6