Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

CSD302 : Design and Analysis of Algorithms Spring 2020

1Solutions
25nd January 2020
Lecturer: Prof. Sandeep Sen

1. Finding Median
If we draw out the entire decision tree for finding the median, we could potentially group the 2
elements smaller/larger than the median,and still preserve enough information to find the median.
5!
In this case we would have 2·2 = 1204
= 30 leaves. So the minimum number of comparisons
required (height of tree) to search in this tree is ceil(log(30)) = 5. We now have a lower bound of
5 on the number of comparisons required.
Following is a method to find the median with 6 comparisons. So, we have an upper bound of 6 on
the problem.
1 median ( a [ 5 ] ) :
2 if a [0] > a [1] : / / comparison 1
3 swap ( a [ 0 ] , a [ 1 ] )
4 if a [2] > a [3] : / / comparison 2
5 swap ( a [ 2 ] , a [ 3 ] )
6 if a [1] > a [3] : / / comparison 3
7 swap ( a [ 3 ] , a [ 1 ] )
8 swap ( a [ 2 ] , a [ 0 ] )
9 if a [4] < a [2] : / / comparison 4
10 x = min ( a [ 1 ] , a [ 2 ] ) / / comparison 5
11 r e t u r n max ( x , a [ 4 ] ) / / comparison 6
12 else :
13 x = min ( a [ 1 ] , a [ 4 ] ) / / comparison 5
14 r e t u r n max ( x , a [ 2 ] ) / / comparison 6

1
2. AVL Trees
Nh = Nh−1 + Nh−2 + 1
N0 = 1 = F3 − 1; N1 = 2 = F4 − 1; N2 = 4 = F5 − 1
Let us assume that Nk−1 = Fk+2 − 1 and Nk−2 = Fk+1 − 1.
Then
Nk = Nk−1 + Nk−2 + 1 = Fk+2 − 1 + Fk+1 − 1 + 1 = Fk+3 − 1
Therefore,
∀k ∈ N, Nk = Fk+3 − 1

( √ )h+3 ( √ )h+3
1 1+ 5 1 1− 5
Nh = √ −√ −1
5 2 5 2
( √ )h+3 ( √ )h+3
1 1+ 5 1 1+ 5
√ − 2 < Nh < √
5 2 5 2

Let the maximum height of AVL tree with n vertices be h′ .

∴ Nh′ ≤ n < Nh′ +1

( √ )h′ +3 ( √ )h′ +4
1 1+ 5 1 1+ 5
√ −2<n< √
5 2 5 2

( √ ) ( √ )
1+ 5 √ 1 + 5 √
(h′ + 3) log2 + log2 ( 5) < log2 (n) < (h′ + 4) log2 + log2 ( 5)
2 2

For
c1 = 0.5, c2 = 2 : c1 h′ < log(n) < c2 h′

∴ h′ ∈ Θ(log(n))

You might also like