SUNY Geneseo Department of Computer Science
Performance
of Alternative Height Algorithms
{Date}
CSci 141, Fall 2003
Prof. Doug Baldwin
Return to
List of Lectures
Previous Lecture
Misc
Exam 2 Wednesday (Nov. 19)
- Lists and Trees
- Rules and format similar to exam 1
- Practice Questions on the Web
- Will try to post solutions tomorrow
Questions?
Guess at closed form for the "Size"
Algorithm in Friday's lecture came mostly from past experience with similar
recurrences.
Height Algorithm
int height()
if ! this.isEmpty()
leftHeight = this.left().height()
rightHeight = this.right().height()
if leftHeight > rightHeight
return 1 + leftHeight
else
return 1 + rightHeight
else
return 0
vs
int height()
if ! this.isEmpty()
if this.left().height() > this.right().Height()
return 1 + this.left().Height()
else
return 1 + this.right().Height()
else
return 0
Mini-assignment: what are the performance consequences
Plan
- Set up recurrences for each algorithm
- Give closed forms asymptotically (Theta(...))
Recurrences
- height w/ variables:
- f(0) = 1
- f(n) = 3 + f(n1) + f(n2) if n > 0
- Closed form: f(n) = 4n + 1
- This is the recurrence from "size" Friday
- = Theta(n)
- [From here on this is pretty much "extra" material -- stuff that
you can probably follow, but that I definitely wouldn't expect you to do on
your own]
- height w/o variables
- recurrence
- f(0) = 1
- f(n ) = 4 + 2f(n1) + f(n2) if n > 0
- where n1 + n2 = n - 1
- Look at extreme cases
- Worst case, largest f()
- n1 big, n2 small
- n1 = n-1, n2 = 0
- Rewrite recurrence for this n1, n2
- f(0) = 1
- f(n) = 5 + 2f(n-1) if n > 0
- = Theta(2n)
- Best case - balanced tree
- n1 = n2 = (n-1)/2
- Rewrite recurrence
- f(0) = 1
- f(n) = 4 + 3f( (n-1)/2 ) if n > 0
- Restrict n to values for which (n-1)/2 is whole, and [ (n-1)/2
] -1 / 2 whole etc
- n = 2i - 1
n = 2i - 1 |
f(n) |
0 = 20 - 1 |
1 |
1 = 21 - 1 |
4 + 3f(0) |
|
= 4 + 3(1) |
3 = 22 - 1 |
4 + 3f(1) |
|
= 4 + 3(4+3(1)) |
|
= 4 + 3(4) + 32(1) |
- Guess: f(n) = 4 (sum from j=0 to i-2 of 3j) + 3i-1
- [I added lots of algebraic details below that I didn't have to explain
in class]
- = Theta( 3log2n )
- = Theta( (2log23)log2n )
[any number can be written as 2 raised to the base 2 log of that number]
- = Theta( (2log23 log2n)
[for any x, y, z, xyz = xyz]
- = Theta( (2log2n log23)
[switching the order of multiplicands in the exponent]
- = Theta( nlog23 ) [2log2n
= n ]
- = Theta( n1.58 )
Next
Inserting new items into a binary search tree
Next Lecture