This preview shows pages 1–6. Sign up to view the full content.
02/10/12
Debasis Mitra, FIT
1
Recursive and
Iterative
Algorithms
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document 02/10/12
Debasis Mitra, FIT
2
What does the following algorithm do?
Algorithm what(n)
(1)
x:=1; y:=1; z:=0;
(2)
for int I:=1 to n2 do
(3)
z := x +y;
(4)
y := x;
(5)
x := z;
end for;
(6)
return z;
End algorithm.
02/10/12
Debasis Mitra, FIT
3
Now this Algorithm?
Algorithm
nowwhat
(n)
(1)
if n = = 1 or 0
then return 1
(2)
else
(3)
return
nowwhat
(n1) +
nowwhat
(n2)
(4)
end if;
End algorithm.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document 02/10/12
Debasis Mitra, FIT
4
Actually the recursion is working like:
Algorithm
nowwhat
(
n
)
(1)create
stack
;
(2)if n>1 then
push
(
stack
,
n
);
(3)int
temp
:= 0;
(4)while
stack
not
empty
do
(5)
int
x
:=
pop
(
stack
);
(6)
if
x
> 1 then
(7)
push
(
stack
,
x
1);
(8)
push
(
stack
,
x
2);
else
(9)
temp
:=
temp
+ 1;
end if;
end while;
(10)
return temp;
End algorithm.
02/10/12
Debasis Mitra, FIT
5
Recursion tree for recursive Fibonacci
number calculation: sample
nw(4)
nw(1)
nw(2)
nw(1)
nw(0)
nw(3)
nw(2)
nw(1)
nw(0)
nw
(4) =
nw
(1) +
nw
(0)
+
nw
(1)
+
nw
(1)
+
nw
(0)
= 5
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview. Sign up
to
access the rest of the document.
This note was uploaded on 02/10/2012 for the course CSE 5211 taught by Professor Dmitra during the Spring '12 term at FIT.
 Spring '12
 Dmitra
 Algorithms

Click to edit the document details