This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Module 4 Generative recursion Theres more to programming than the list template? CS 116: Introduction to Computer Science 2 Daniel G. Brown/Troy Vasiga, University of Waterloo 4.1 Purpose of Module 4 Algorithms: generative recursion Standard algorithms for typical data-processing problems How to successfully design generative recursive code Readings: HtDP 25, 26, Intermezzo 5 4.2 1 Algorithms: generative recursion Less obvious recursion All of our recursions so far have been natural: simple base case straightforward inductive case that works toward that base case. We called this structural recursion. Some examples of recursion arent nearly so clean Each run through a procedure may get us one step closer to the goal, but how we get there may be a lot more uncertain. We may also not know how many steps the algorithm will take. Or, each step might be more complicated in its own right. 4.3 More complex recursion? Why might we use more complex recursion? to make the program faster, to solve a hard problem where structural recursion isnt the obvious way to solve it. We will call this style of recursion generative recursion, because we have to think in order to identify the recursive cases in the development: we must generate them. 4.4 2 Sorting algorithms 2.1 Insertion sort Sorting Possibly the most basic example of doing this: sorting a list of numbers. 1 ;; sort-list: (listof num) (listof num) ;; produces a list with all of the same elements as lst, ;; but in sorted order from smallest to largest ;; Example: ;; (sort-list (list 1 4 3 2)) (list 1 2 3 4) An algorithm from 115 used structural recursion: To sort a list: Sort all but the first element of the list. Then, insert the first element into its proper place in the sorted remainder of the list. ( define ( sort-list lst ) ( cond [( empty ? lst ) empty ] [ else ( insert ( first lst ) ( sort-list ( rest lst )))])) Do you remember how to write the function insert ? 4.5 Finishing off insertion sort ;; insert: num (listof num) (listof num) ;; insert produces a sorted list like sortedlist, except ;; item is inserted into the correct position ( define ( insert item sortedlist ) ( cond [( empty ? sortedlist ) ( list item )] [(< item ( first sortedlist )) ( cons item sortedlist )] [ else ( cons ( first sortedlist ) ( insert item ( rest sortedlist )))])) Both sort-list and its helper function, insert , use natural recursion. Its especially clean in the case of sort-list . You could actually write them both using foldr . This algorithm is called insertion sort . 4.6 2.2 Selection sort Selection sort Another way of sorting a list: Remove the smallest element from the list Sort whats left Put the smallest element first....
View Full Document