11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

122 Chap. 4 Lists, Stacks, <strong>and</strong> QueuesCurrptrβCall fact(4)Currptrβ1CurrptrCurrptrββ 1n 4 n 4Currptr β Currptr βCall fact(3) Call fact(2)CurrptrCurrptrββ2 2n 3 n 3CurrptrnCurrptrβ3n 214βCall fact(1)CurrptrCurrptrnCurrptrββ2n 3Currptrβ1 14 n 4β Currptr βReturn 1 Return 2CurrptrβReturn 6Return 24Figure 4.22 Implementing recursion with a stack. β values indic<strong>at</strong>e the addressof the program instruction to return to after completing the current function call.On each recursive function call to fact (as implemented in Section 2.5), both thereturn address <strong>and</strong> the current value of n must be saved. Each return from factpops the top activ<strong>at</strong>ion record off the stack.current value for n (which is 4), is saved on the stack. Function fact is invokedwith input parameter 3.In similar manner, another recursive call is made with input parameter 2, requiringth<strong>at</strong> the address from which the call is made (say β 2 ) <strong>and</strong> the current valuefor n (which is 3) are stored on the stack. A final recursive call with input parameter1 is made, requiring th<strong>at</strong> the stack store the calling address (say β 3 ) <strong>and</strong> currentvalue (which is 2).At this point, we have reached the base case for fact, <strong>and</strong> so the recursionbegins to unwind. Each return from fact involves popping the stored value forn from the stack, along with the return address from the function call. The returnvalue for fact is multiplied by the restored value for n, <strong>and</strong> the result is returned.Because an activ<strong>at</strong>ion record must be cre<strong>at</strong>ed <strong>and</strong> placed onto the stack foreach subroutine call, making subroutine calls is a rel<strong>at</strong>ively expensive oper<strong>at</strong>ion.While recursion is often used to make implement<strong>at</strong>ion easy <strong>and</strong> clear, sometimes

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!