When viewing the below MIT 6.001 course video, at 28:00 the instructor marks this algorithm as iteration. But, at 30.27 he says both this and the actual "recursive" algorithms are recursive. The function is calling itself with a base case, so how is this iteration?
https://www.youtube.com/watch?v=dlbMuv-jix8&list=PLE18841CABEA24090&index=2
private int iterativeSum(int x, int y)
{
System.out.println("x "+x+" y "+y);
if(x == 0)
{
return y;
}
return iterativeSum(--x, ++y);
}
The instructor seems to be more interested in how it's executed, rather than how the code is written. There's a big difference between those two, but that's a whole other conversation (but notably, some languages will compile recursions as iterations, as an example).
In this case, it is iteration when you hold the whole state in one place and repeatedly work on that one piece of data. It is recursion when you have a stack of states and add to the stack, then eventually collapse the stack back down to an answer.
In the instructor's example at 31:00, he shows this as being iteration when there is one bit of paper that holds the entire state of the work done so far, and any one guy can take it and eventually produce the final answer.
In the example of recursion at 32:20, Joe has his own notes on the problem, and only passes on notes about a subsection of the problem. Harry then has enough information for his subsection of the problem, but the entire problem still requires Joe to hold on to his own information to process Harry's results when he gets them back from Harry.
You have a whole stack of people, with more people being added to the stack until one of them has a problem simple enough to do it by himself, and he can return his answer right away, which means the second last guy now has a simpler problem and can now return his answer, and so on until the entire stack of people collapses back down into one last (first) person who then produces the final answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With