03-Example - Stackspan PDF
03-Example - Stackspan PDF
Data Structures
and Algorithms
1
Trying to overcome the
limitations of Array based
Stacks and Queues
Create B
B
Copy A into B
Reassign reference A to
the new array
A
A Growable Array-Based Stack
Idea: when the array S is full, replace it with a larger one and continue
processing push operations.
Algorithm push(obj):
if size() = N then
A ← new array of length f(N)
for i ← 0 to N - 1
A[i] ← S[i]
S ← A
t ← t + 1
S[t] ← obj
• How large should the new array be?
– tight strategy (add a constant): f(N) = N + c
Phase 2: 2 c + c + 1 + (c-1) = 4c
= 2 i+1
Growth Strategy
???
n = 1+ Σ 1 2i-1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 n
Performance of the Growth Strategy
• m
• S = ∑ ri = 1 + r + r2 + … + rm = (rm+1-1)/(r-1)
i=0
•b=a log b
a -> b = 2 log b -> n=2 log n
S 1 1 2 3 1
Quadratic Algorithm
Algorithm spans1(X, n)
Input array X of n integers
Output array S of spans of X #
S ← new array of n integers n
for i ← 0 to n − 1 do n
s←1 n
while s ≤ i ∧ X[i − s] ≤ X[i] 1 + 2 + …+ (n − 1)
s←s+1 1 + 2 + …+ (n − 1)
S[i] ← s n
return S 1
5 Si = i– j
3
2
0
0 1 2 3 4 5 6 7
X
8
6
5
Index: 0, 1, 2, 3, 4, 5, 6, 7
3 X : 6, 3, 4, 1, 2, 3, 5, 4
S : 1, 1, 2, 1, 2, 3, 6, 1
2
0
0 1 2 3 4 5 6 7
1 (3)
0 (6)
2(4) 3(1)
0(6) 2(4) 4(2)
0(6) 2(4)
0(6)
• We keep in a stack the indices of the elements visible when “looking
back”
– We set S[i] ← i - j