Avoiding Recursion
Projects
9.26 |
Simpler algorithms often have smaller constant factors associated with their running-time than more sophisticated algorithms. For sufficiently small arrays, for example, insertion sort may actually be faster than Quicksort. Modify the Quicksort algorithm so that, if the region to be sorted is below a certain length, insertion sort is used instead. Using the timing techniques from Chapter 7, find an appropriate length at which to make this change. |
9.27 |
Modify the recursive fibo() method (Figure 9-33) to simulate the call stack manually. Begin by rearranging the method so that only one step or recursive invocation occurs on each line. Define a class Frame which simulates a call frame. Finally, modify the fibo() method so that it begins by pushing a single Frame onto a fresh stack. The method then repeatedly pops the stack and handles the resulting Frame. This may result in pushing other Frames onto the stack. This loop continues until the stack is emptythat is, until there is no more work to do. This project should leave you with a page or two of codeand a greater appreciation of recursion! |