CSC151.01 2006S, Class 41: Introduction to Sorting Admin: * Due: HW13. * Next Thursday: Thursday extra on VideoScheme. * Homework for Tuesday: A guessing game. * Reading for Monday: Sorting. * Prospies! Paul from Houston Overview: * Notes on HW12. * The problem of sorting, revisited. * Writing sorting algorithms. * Examples: Insertion, Selection, etc. * Formalizing the problem. Computer science is the study of algorithms! Good computer scientists look for general problems for which to write algorithms * Searching * Binary search is a good algorithm, but requires a sorted vector * Q: How do we get sorted vectors? Once you've identified a problem, how do you write an algorithm? * One technique: Look at similar problems and their algorithms * Another: Remember key patterns for algorithm design and use them * Intuition: Try doing it by hand and then formalize what you did Tim the Second's strategy for sorting people by name * Find all the A's and shove 'em at the end * Find all the B's and shove 'em at the end * Find all the C's and shove 'em at the end * ... Unresolved issues: * What if more than one person starts with the same letter? * What about those spaces we created? * What if you're comparing something that isn't names (or that is not as well distributed as strings)? Solving the "other types" * Intead of "A's" use "the thing that should come first" * Given a list, how do we find the smallest thing What can we do about the spaces we've created? * Assumes we have a vector * Instead of putting the thing at the end, swap it to "the front" (or right after the last thing we put at the front) * This is a famous sorting algorithm, called selection sort Another common sense algortihm: * Split the list or vector into "sorted" and "unsorted" portions * Repeatedly remove one thign from the unsorted portion and put it in the sorted portion * This is also a famous sorting algorithm, called insertion sort (Or sorta called insertion) Problems: * Translate these nice, easy-to-understand algorithms into nice, easy-to-understand Scheme * Think carefully about what it means to sort * What parameters should we provide to an algorithm that sorts vectors ;;; Procedure: ;;; insertion-sort! ;;; Parameters: ;;; vec, a vector ;;; comes-before?, a binary predicate ;;; Purpose: ;;; sorts vec ;;; Preconditions: ;;; comes-before? is transitive and reflexive (works the way you'd ;;; expect it to work ;;; Postconditions: ;;; vec is now sorted. (define insertion-sort! (lambda (vec comes-before?)