Presentation is loading. Please wait.

Presentation is loading. Please wait.

A Recipe for Algorithm Design Or, What to do when the data type doesn't match the function…yet.

Similar presentations


Presentation on theme: "A Recipe for Algorithm Design Or, What to do when the data type doesn't match the function…yet."— Presentation transcript:

1 A Recipe for Algorithm Design Or, What to do when the data type doesn't match the function…yet.

2 The Recipe Before Chapter 25 Data analysis and design Contract, purpose, header Examples Template The thing with the dot dot dots. On lists, we fully captured the template with the fold function. Look! Ma! No dot dot dots! We said it can do "almost everything"…

3 Quicksort Breaks Template (define (qsort l) (cond [(empty? l) empty] [else (local ((define pivot (first l)) (define other (rest l))) (append (qsort [filter (lambda (x) (< x pivot)) other]) (list pivot) (qsort [filter (lambda (x) (>= x pivot)) other])))]))

4 Quicksort Still Terminates (define (qsort l) (cond [(empty? l) empty] [else (local ((define pivot (first l)) (define other (rest l))) (append (qsort [filter (lambda (x) (< x pivot)) other]) (list pivot) (qsort [filter (lambda (x) (>= x pivot)) other])))]))

5 The Notsoquicksort (define (qsort l) (cond [(empty? l) empty] [else (local ((define pivot (first l)) (define other l)) (append (qsort [filter (lambda (x) (< x pivot)) other]) (qsort [filter (lambda (x) (>= x pivot)) other])))]))

6 A Recipe for General Algorithms Data analysis and design Contract, purpose, header Examples Template A bit more flexible than before Termination argument Needs to be done, explicitly, seperately

7 Example termination argument ; At each step, quick-sort partitions the list into two ; sublists using smaller-items and larger-items. Each ; function produces a list that is smaller than the ; input (the second argument), even if the threshold ; (the first argument) is an item on the list. Hence ; each recursive application of quick-sort consumes ; strictly shorter list than the given one. Eventually, ; quick-sort receives and returns empty. Without such an argument an algorithm must be considered incomplete.

8 Why Generative Recursion? What if we can chose between A structural solution and A generative solution? Often, the second can be much faster Book has very nice example Greatest-common-divisor (GCD) gcd(6,9)=3, gcd (99, 18) = 9, etc.


Download ppt "A Recipe for Algorithm Design Or, What to do when the data type doesn't match the function…yet."

Similar presentations


Ads by Google