130 likes | 146 Views
Lecture 11: Sorting Grounds and Bubbles. David Evans http://www.cs.virginia.edu/evans. Coffee Bean Sorting in Guatemala. CS200: Computer Science University of Virginia Computer Science. Menu. Find Most Sorting. find-most-caffeinated. (define (find-most-caffienated menu) (insertl
E N D
Lecture 11: Sorting Grounds and Bubbles David Evans http://www.cs.virginia.edu/evans Coffee Bean Sorting in Guatemala CS200: Computer Science University of Virginia Computer Science
Menu • Find Most • Sorting CS 200 Spring 2003
find-most-caffeinated (define (find-most-caffienated menu) (insertl (lambda (c1 c2) (if (> (coffee-caffeine-rating c1) (coffee-caffeine-rating c2)) c1 c2)) menu (make-coffee “water” 0.00 0))) ;; we should only water if there are no coffees ;; on the menu CS 200 Spring 2003
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)))) CS 200 Spring 2003
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) > (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
Sorting CS 200 Spring 2003
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 CS 200 Spring 2003
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))))) CS 200 Spring 2003
sort-menu (define (sort-menu 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) CS 200 Spring 2003
All Sorts (define (sort cf lst) (if (null? lst) lst (let ((most (find-most cf lst))) (cons most (sort cf (delete lst most)))))) CS 200 Spring 2003
Caffeine Sorts (define (sort-menu-by-caffeine menu) (sort (lambda (c1 c2) (> (coffee-caffeine-rating c1) (coffee-caffeine-rating c2))) menu)) CS 200 Spring 2003
find-most (define (find-most cf lst) (insertl (lambda (c1 c2) (if (cf c1 c2) c1 c2)) lst (car lst))) CS 200 Spring 2003
Charge • PS3 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 (n2) • How does it relate to grade inflation CS 200 Spring 2003