Lecture 11 Sorting Grounds and Bubbles Coffee Bean
Lecture 11: Sorting Grounds and Bubbles Coffee Bean Sorting in Guatemala CS 200: Computer Science David Evans University of Virginia 10 February 2003 CS 200 Spring 2003 http: //www. cs. virginia. edu/evans Computer Science
Menu • Find Most • Sorting 10 February 2003 CS 200 Spring 2003 2
find-most-caffeinated (define (find-most-caffienated menu) (insertl (lambda (c 1 c 2) (if (> (coffee-caffeine-rating c 1) (coffee-caffeine-rating c 2)) c 1 c 2)) menu (make-coffee “water” 0. 00 0))) ; ; we should only water if there are no coffees ; ; on the menu 10 February 2003 CS 200 Spring 2003 3
find-most-caffeinated (define (find-most-caff menu) (if (null? menu) (make-coffee “water" 0. 00 0) (let ((rest-most-caff (find-most-caff (cdr menu)))) (if (> (coffee-caffeine-rating (car menu)) (coffee-caffeine-rating rest-most caff)) (car menu) rest-most-caff)))) 10 February 2003 CS 200 Spring 2003 4
Comparing Processes > (trace >) (>) > (find-most-caff todays-menu) |(> 57 -1) |#t |(> 15 57) |#f |(> 12 57) |#f |(> 92 57) |#t |(> 85 92) |#f ("BEN'S Expresso Noir Supreme" 17. 23. 92) 10 February 2003 > (find-most-caffienated todays-menu) |(> 57 -1) |#t |(> 15 57) |#f |(> 12 57) |#f |(> 92 57) |#t |(> 85 92) |#f ("BEN'S Expresso Noir Supreme" 17. 23. 92) CS 200 Spring 2003 5
Sorting 10 February 2003 CS 200 Spring 2003 6
Simple Sorting • We know how to find-most-caffeinated • How do we sort list by caffeine rating? • Use (find-most-caffeinated menu) to find the most caffeinated • Remove it from the menu • Repeat until the menu is empty 10 February 2003 CS 200 Spring 2003 7
Delete ; ; ; Evaluates to the list parameter with ; ; ; first instance of el removed. (define (delete lst el) (if (null? lst) (error "Element not found!") (if (eq? (car lst) el) (cdr lst) (cons (car lst) (delete (cdr lst) el))))) 10 February 2003 CS 200 Spring 2003 8
sort-menu (define (sort-menu) (if (null? menu) menu (let ((most-caff (find-most-caffeinated menu))) (cons most-caff (sort-menu (delete menu most-caff)))))) How can we generalize this? (e. g. , sort by price also) 10 February 2003 CS 200 Spring 2003 9
All Sorts (define (sort cf lst) (if (null? lst) lst (let ((most (find-most cf lst))) (cons most (sort cf (delete lst most)))))) 10 February 2003 CS 200 Spring 2003 10
Caffeine Sorts (define (sort-menu-by-caffeine menu) (sort (lambda (c 1 c 2) (> (coffee-caffeine-rating c 1) (coffee-caffeine-rating c 2))) menu)) 10 February 2003 CS 200 Spring 2003 11
find-most (define (find-most cf lst) (insertl (lambda (c 1 c 2) (if (cf c 1 c 2)) lst (car lst))) 10 February 2003 CS 200 Spring 2003 12
Charge • PS 3 Due Wednesday – Lab Hours: Tonight, 6 -7: 30 PM in Small Hall • Think about faster ways of sorting (next time) • Read Tyson’s essay (before Friday) – How does it relate to (n 2) – How does it relate to grade inflation 10 February 2003 CS 200 Spring 2003 13
- Slides: 13