HW #2

advertisement
CS 583: Data Structures and Analysis of Algorithms: Fall 2006: D. Kaznachey
Home Work #2
Due by: November 14, 2006
Submit:
 Hard copy in the class (preferred), or
 By e-mail (before the class start) to TA at cs583ta@gmail.com
o Attach the submission in a separate file, and double-check that it’s not
empty.
o Prefix the file name with the student’s last name, e.g. JonesHw2.doc.
 Indent a pseudocode properly.
1. (5 points) Write a recursive procedure OS-Key-Rank(T, k) that takes as input an orderstatistics tree T and a key k and returns the rank of k in the dynamic set represented by T
(see exercise 14.1-4). Calculate the running time of the algorithm.
Solution:
Recursive-OS-Key-Rank (x, k)
1 if key[x] = k
2
return 1
3 else
4
if k < key[x]
5
return Recursive-OS-Key-Rank (left[x], k)
6
else
7
return size[x] + Recursive-OS-Key-Rank (right[x], k)
OS-Key-Rank (T, k)
1 return Recursive-OS-Key-Rank (root[T], k)
The above algorithm performs a constant number of operations at each tree level, and
iterates at most h (depth of the tree) times. Since h = O(lg n), the running time is O(lg n).
2. (5 points) Write a procedure B-Tree-Predecessor (T, k) to find a predecessor of a
given key stored in a B-tree (see exercise 18.2-3). (A predecessor is a key immediately
preceding k in the linear order of all keys stored in the B-tree.) Argue about the
correctness of your algorithm.
Solution:
B-Tree-Predecessor (T, k)
1 (x,i) = B-Tree-Search (root[T], k)
2 if leaf[x]
3
if i = 1 // k is a minimum key in T
4
return NIL
5
else
6
return (x, i-1)
7 Disk-Read (ci[x])
CS 583: Data Structures and Analysis of Algorithms: Fall 2006: D. Kaznachey
8
return B-Tree-Maximum (ci[x])
// Find the maximum key in a subtree x
B-Tree-Maximum (x)
1 if leaf[x]
2
return (x, n[x])
3 Disk-Read (cn[x]+1[x])
4 return B-Tree-Maximum (cn[x]+1[x])
The correctness of the above algorithm can be argued as follows.
 Consider a node x with key k as follows: keyi-1 <= k <= keyi+1
 The predecessor p of k cannot be located in the previous (parent) level:
o p <= k <= p* since ki-1 >= p by B-tree definition.
 Hence p(k) is located between ki-1 and k, and can be retrieved by getting the
maximum key at the subtree rooted at x.
3. (Bonus 1 point) Prove the following formula (see exercise C.1-7)
(ki) = (k-1i) + (k-1i-1)
Solution:
When choosing i elements from k, we first consider choosing i elements from (k-1).
When adding an additional element k* we need to only add combinations of k* with (i-1)
elements from (k-1). This gives the above formula.
Download