Professional Documents
Culture Documents
Divide Conquer 2
Divide Conquer 2
Divide Conquer 2
Algorithm Notes
Divide and Conquer-2
By
Dr. K. V. Arya
ABV-IIITM, Gwalior, India
Summary
More examples of divide and conquer.
Selection in average time O(n).
Therefore , n ≥2
1 k 2 n 1
T (n) T (n j 1) T ( j ) n 1
n j 0 j k
1 n 1 n 1
T ( j ) T ( j ) n 1
n j n k 1 j k
Analysis Contd..
What value of k maximizes
n 1 n 1
j n k 1
T ( j) T ( j) ?
j k
Decrementing the value of k deletes a term from the left sum, and
inserts a term into the right sum. Since T is the running time of an
algorithm , it must be monotonic nondecreasing.
Analysis Contd…
Hence, we must choose k=n-k+1. Assume n is odd (the case
where n is even is similar). This means we choose k=(n+1)/2.
write m=(n+1)/2 (shorthand for this diagram only.)
k=m
Analysis Contd..
k=m-1
Therefore,
n 1
2
T ( n)
n
T ( j) n 1
j ( n 1) / 2
Analysis Contd..
Claim that T(n) ≤ 4(n-1). Proof by induction on n. The claim is
true for n=1. Now, suppose that T(j) ≤ 4(j-1) for all j < n. Then,
2 n 1
T (n )
T ( j)
n 1
n j ( n 1) / 2
8 n 1
( j 1)
n 1
n j ( n 1) / 2
8 n 2
j n 1
n j ( n 1) / 2
Analysis Contd..
8 ( n 1)( n 2) ( n 3)( n 1)
n 1
n 2 8
4n 2 12n 8 n 2 4n 3 n 1
1
n
5
3n 8 n 1
n
4n 4
Move all the disks from peg 1 to peg 3 using peg 2 as workspace
without ever placing a larger disk on a smaller disk
The Towers of Hanoi
To move n disks from peg i to peg j use peg k as workspace
Hence,
T ( n) 2T ( n 1) 1
2(2T (n 2) 1) 1
How many Moves? Contd..
4T ( n 2) 2 1
4( 2T ( n 3) 1) 2 1
8T ( n 3) 4 2 1
i 1
2 T (n i ) 2 j
i
j 0
n2
2 n 1
T (1) 2 j
j 0
2n 1
The End of Universe
At one move per second that is
1.84 x 1019 seconds
= 3.07 x 1017 minutes
= 5.12 x 1015 hours
= 2.14 x 1014 days
= 5.85 x 1011 years
Current age of universe is ≈ 1010 years
The Answer to Life, the Universe , and
Everything
2 –
64 1
= 18, 446 , 744, 073 ,709, 552 , 936
A Sneaky Algorithm
What if monks are not good at recursion?
Imagine that the pegs are arranged in a circle. Instead, of numbering the pegs ,
think of moving the disks one place clockwise or anticlockwise.
Impress your friends
If there are an odd number of disks :
Start by moving the smallest disk in anticlockwise direction.
Alternate between doing this and the only other legal move.
Even
A Formal Algorithm
Let D be a direction either clockwise or anticlockwise. Let D be the opposite
direction.
To move n disks in the direction D , alternate between the following two
moves:
If n is odd move the smallest disk in direction D. If n is even move the
smallest disk in direction D.
Make the only other legal move.