12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 4.2 Stacks 129Currptr β 1CurrptrnCurrptrβ 23β 1CurrptrnCurrptrnCurrptrβ 32β 23β 1Currptr β 2n 4 n 4n 4Currptr β Currptr β Currptr β Currptr βCall fact(4) Call fact(3) Call fact(2) Call fact(1)nCurrptrnCurrptr3β 14βReturn 1CurrptrnCurrptrβ 14βReturn 2CurrptrβReturn 6Return 24Figure 4.21 Implementing recursion with a stack. β values indicate the addressof the program instruction <strong>to</strong> return <strong>to</strong> after completing the current function call.On each recursive function call <strong>to</strong> fact (from Section 2.5), both the return address<strong>and</strong> the current value of n must be saved. Each return from fact pops the<strong>to</strong>p activation record off the stack.Consider what happens when we call fact with the value 4. We use β <strong>to</strong>indicate the address of the program instruction where the call <strong>to</strong> fact is made.Thus, the stack must first s<strong>to</strong>re the address β, <strong>and</strong> the value 4 is passed <strong>to</strong> fact.Next, a recursive call <strong>to</strong> fact is made, this time with value 3. We will name theprogram address from which the call is made β 1 . The address β 1 , along with thecurrent 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, requiringthat the address from which the call is made (say β 2 ) <strong>and</strong> the current valuefor n (which is 3) are s<strong>to</strong>red on the stack. A final recursive call with input parame-

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

Saved successfully!

Ooh no, something went wrong!