CS 332: Algorithms: Medians and Order Statistics Structures For Dynamic Sets
CS 332: Algorithms: Medians and Order Statistics Structures For Dynamic Sets
CS 332: Algorithms: Medians and Order Statistics Structures For Dynamic Sets
Homework 3
On the web shortly
Due Wednesday at the beginning of class (test)
smallest element
The minimum is thus the 1st order statistic
The maximum is (duh) the nth order statistic
The median is the n/2 order statistic
If n is even, there are 2 medians
element of a set
Two algorithms:
A practical randomized algorithm with O(n)
A[q]
p
A[q]
q
A[q]
q
1 n 1
T max k , n k 1 n
n k 0
2 n 1
T k n
n k n / 2
x?
x?
cn cn 20 n
cn if c is big enough
n/5 ???
n/5
Substitute T(n) =???
cn
Combine fractions
???
smaller
Geometric progression!
Structures
Done with sorting and order statistics for now
Ahead of schedule, so
Next part of class will focus on data structures
We will get a couple in before the first exam
Yes, these will be on this exam
Dynamic Sets
Next few lectures will focus on data structures
x), Predecessor(S, x)
They may also support modifying operations like:
Insert(S, x), Delete(S, x)
H
D
TreeWalk(x)
TreeWalk(left[x]);
print(x);
TreeWalk(right[x]);
A: prints elements in sorted (increasing) order
This is called an inorder tree walk
Preorder tree walk: print root, then left, then right
Postorder tree walk: print left, then right, then root
B
A
H
D
increasing order
F
B
A
H
D
k != key[x])
F
B
D
C
TreeInsert()?
A: O(h), where h = height of tree
What is the height of a binary search tree?
A: worst case: h = O(n) when tree is just a
linear string of left or right children
Well keep all analysis in terms of h for now
Later well see how to maintain h = O(lg n)
BSTSort(A)
for i=1 to n
TreeInsert(A[i]);
InorderTreeWalk(root);
(n lg n)
What will be the running time in the
Argue that this is
Worst case?
Average case? (hint: remind you of anything?)
for i=1 to n
TreeInsert(A[i]);
InorderTreeWalk(root);
3 1 8 2 6 7 5
1 2
8 6 7 5
2
6 7 5
5
6
5
in a different order
In previous example
Everything was compared to 3 once
Then those items < 3 were compared to 1 once
Etc.
operation
Draw Fig 13.2
What is the successor of node 3? Node 15?
Node 13?
What are the general rules for finding the
successor of node x? (hint: two cases)
in right subtree
x has no right subtree: successor is first ancestor of
x whose left child is also ancestor of x
Intuition: As long as you move to the left up the tree,
3 cases:
x has no children:
Remove x
Splice out x
D
C
K
Example: delete K
or H or B
The End
Up next: guaranteeing a O(lg n) height tree