L08
L08
On
Stacks, Recursion
1. [Initialize] TOP=NULL.
2. [Push boundary values of A onto stack when A has 2 or more elements]
If N>1, then TOP:=TOP+1, LOWER[1]:=1 and UPPER[1]:=N.
3. Repeat Step 4 to 7 while TOP!= NULL.
4. [Pop sub list from stack]
Set BEG:=LOWER[TOP], END:=UPPER[TOP]
TOP:=TOP-1.
5. Call QUICK(A,N,BEG,END,LOC). [Procedure 6.5]
6. [Push left sub list onto stacks when it has 2 or more elements]
If BEG<LOC-1 then:
TOP:=TOP+1, LOWER[TOP]:=BEG,
UPPER[TOP]=LOC-1
[End of If structure].
7. [Push right sub list onto stacks when it has 2 or more elements]
If LOC+1 < END then:
TOP:=TOP+1, LOWER[TOP]:= LOC+1,
UPPER[TOP]:= END
[End of If structure]
[End of Step 3 loop].
8. Exit
Sowmitra Das, Lecturer,CSE,
PCIU
30 20 10 7 40 50 60 80 100
[1] [2] [3] [4] [5] [6] [7] [8] [9]
6 9 LOC=5 second sublist
TOP:=NULL First sublist
1 4 9>1 ? Yes TOP:=TOP+1=1, LOWER[1]:=1, UPPER[1]:=9
Repeat TOP=!NULL.
UPPER
LOWER LOWER UPPER Pop sub list from STACKs
Set BEG:=LOWER[TOP]=1, END:=UPPER[TOP] =9
TOP:=TOP-1.=0
Call QUICK(A,N,1,9,LOC).
LOC=5
[Push left sub list onto stacks when it has 2 or more elements]
[Push right sub list onto stacks when it has 2 or more elements]
UPPER LOWER UPPER
LOWER
Sowmitra Das,<Lecturer,CSE,
If LOC+1(6) END(9) ? yes [Right sublist’s starting position=loc+1
PCIU
30 20 10 7 40 50 60 80 100
7 9 [1] [2] [3] [4] [5] [6] [7] [8] [9]
First sublist second sublist
4 Repeat TOP=!NULL.
1
Pop sub list from STACKs LOC=6
Set BEG:=LOWER[TOP]=6, END:=UPPER[TOP] =9
LOWER UPPER
TOP:=TOP-1.=2-1=1
Call QUICK(A,N,6,9,LOC).
LOC=6
UPPER
Pop sub list from STACKs
LOWER
Set BEG:=LOWER[TOP]=7, END:=UPPER[TOP] =9
TOP:=TOP-1.=2-1=1
Call QUICK(A,N,7,9,LOC).
LOC=7
Call QUICK(A,N,8,9,LOC).
LOC=8
Call QUICK(A,N,1,4,LOC).
LOC=4
Call QUICK(A,N,1,3,LOC).
LOC=1
Call QUICK(A,N,2,3,LOC).
LOC=3
2 3
[Push left sub list onto stacks when it has 2 or more elements]
• Disks of different sizes (call the number of disks "n") are placed on the left
hand post,
• arranged by size with the smallest on top.
• You are to transfer all the disks to the right hand post in the fewest
possible moves, without ever placing a larger disk on a smaller one.
The object is to move all the disks over to another pole. But you cannot
place a larger disk onto a smaller disk.
• How many moves will it take to transfer n disks from the left post to the right
post?
•
Let's look for a pattern in the number of steps it takes to move just one, two, or three
disks. We'll number the disks starting with disk 1 on the bottom.1 disk: 1 move
• Move 1: move disk 1 to post C
• B. Recurrence relations
• Let TN be the minimum number of moves needed to solve the puzzle with N disks. From the previous
section T1 = 1, T2 = 3 and T3 = 7
• A trained mathematician would also note that T0 = 0. Now let us try to derive a general formula.