Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
– Find ?
• How did we locate this node?
– Insert ?
– Delete ?
– buildTree ?
3 4
1
Recall: Amortized Complexity Recall: Amortized Complexity
If a sequence of M operations takes O(M f(n)) time, • Is amortized guarantee any weaker than worstcase?
we say the amortized runtime is O(f(n)).
• Is amortized guarantee any stronger than averagecase?
• Worst case time per operation can still be large, say O(n)
• Worst case time for any sequence of M operations is O(M f(n)) • Is average case guarantee good enough in practice?
Average time per operation for any sequence is O(f(n)) • Is amortized guarantee good enough in practice?
B C C D B C C D
11 12
2
Splay: Zig-Zag* Splay: Zig-Zig*
g k
g k
p p
W Z
p g p
X k g
X Y
k
W X Y Z W
Y Z W X
Special Case for Root: Zig Does Splaying Help Every Node?
root p k root
k p
Z X
X Y Y Z
Only amortized guarantee!
Relative depth of p, Y, Z? Relative depth of everyone else?
Let’s see an example…
Why not drop zig-zig and just zig all the way?
15 16
3
Finally… Another Splay: Find(4)
1 6 6 6
6 1 1 1
? ?
3 3 3 4
Find(4)
2 5 2 5 2 5 3 5
4 4 4 2
19 20
3 5 2
21 22
23 24
4
Splay Operations: Find Splay Operations: Insert
• Find the node in normal BST manner • Insert the node in normal BST manner
• Splay the node to the root • Splay the node to the root
– if node not found, splay what would have been its parent
25 26
splay L
k
find(k) delete k max
L R R
L R
L R <k >k
Splay on the maximum element in L, then attach R
9 9
7 7 29 30
5
Splitting Splays Aha, Another Way to Insert!
split(k)
Insert(k)
splay k
split(k)
T L R
L R
<k >k L R
void split(Node * root, Node *& left,
Node *& right, Object k) {
Node * target = root->find(k);
splay(target);
if (target < k) { OR
void insert(Node *& root, Object k) {
left = target->left;
Node * left, * right;
target->left = NULL;
split(root, left, right, k);
right = target; L R L R
root = new Node(k, left, right); Interesting note: split-and-insert was
}
... ≤x >x <x ≥x } the original algorithm. But insert-
31 32
and-splay has better constants
}