David Evans http://www.cs.virginia.edu/evans Lecture 11: Sorting Grounds and Bubbles Coffee Bean Sorting in Guatemala CS200: Computer Science University of Virginia Computer Science David Evans http://www.cs.virginia.edu/evans
Menu Find Most Sorting 10 February 2003 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 10 February 2003 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)))) 10 February 2003 CS 200 Spring 2003
Comparing Processes > (trace >) (>) > (find-most-caff todays-menu) |(> 57 -1) |#t |(> 15 57) |#f |(> 12 57) |(> 92 57) |(> 85 92) ("BEN'S Expresso Noir Supreme" 17.23 . 92) > (find-most-caffienated todays-menu) |(> 57 -1) |#t |(> 15 57) |#f |(> 12 57) |(> 92 57) |(> 85 92) ("BEN'S Expresso Noir Supreme" 17.23 . 92) 10 February 2003 CS 200 Spring 2003
Sorting 10 February 2003 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 10 February 2003 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))))) 10 February 2003 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) 10 February 2003 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)))))) 10 February 2003 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)) 10 February 2003 CS 200 Spring 2003
find-most (define (find-most cf lst) (insertl (lambda (c1 c2) (if (cf c1 c2) c1 c2)) lst (car lst))) 10 February 2003 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 10 February 2003 CS 200 Spring 2003