60 likes | 78 Views
Learn how vectors provide a solution to the capacity limit problem in array-based implementations such as stacks, queues, and array lists. Compare incremental and doubling strategies for resizing arrays. Analyze the amortized time complexity of push operations using both strategies.
E N D
Growing Arrays Vectors
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 array-based implementations? Vectors
Growable Array Implementations (of stack, queue, array list, etc…) Algorithmpush(o) ift=S.length 1then A new array of size … fori0tot do A[i] S[i] S A tt +1 S[t] o • 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 • doubling strategy: double the size Vectors
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 Vectors
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 + 2c + 3c + 4c + … + kc)= n + 2c(1 + 2 + 3 + … + k) = n + 2c × k(k + 1)/2 = O(n+k2) • Since c is a constant, T(n) = O(n+k2) = O(n+(n/c)2) =O(n2) • The amortized time of 1 push is O(n2)/n = O(n) Vectors
geometric series 2 4 1 1 8 Doubling Strategy Analysis • We replace the array k = log2n times • The total time T(n) of a series of n push operations is proportional to n + 2×(1 + 2 + 4 + 8 + …+ 2k)= n+ 2×(2k + 1-1) = 3n -2 = O(n) • The amortized time of 1 push is O(n)/n = O(1) Vectors