Download presentation
Presentation is loading. Please wait.
Published byΓολγοθά Παπαϊωάννου Modified over 6 years ago
1
Vectors 11/23/2018 1:03 PM Growing Arrays Vectors
2
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
3
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 doubling strategy: double the size 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 Vectors
4
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
5
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( … + 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
6
Doubling Strategy Analysis
We replace the array k = log2 n times The total time T(n) of a series of n push operations is proportional to n + 2×( …+ 2k) = n + 2×(2k ) = 3n -2 = O(n) The amortized time of 1 push is O(n)/n = O(1) geometric series 1 2 4 8 Vectors
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.