CSC297.Java, Class 25: Sorting Admin: * Next Monday, other room (2435, probably) * Recurrence conclusions * New homework: * Write the Sorter interface * Write an InsertionSorter or a SelectionSorter class * Show that you can use it to sort some strings Overview: * What do you sort? * Big picture: In-place or external * Costs? * Insertion Sort * Selection Sort /Hw: Analyze/ * f(n) = c*n + 2*f(n/2) * Analysis: * f(n) = c*n + 2*(c*n/2 + 2*f(n/4)) * f(n) = c*n + c*n + 4*f(n/4) * f(n) = 2*c*n + 4*f(n/4) * f(n) = 2*c*n + 4*(c*n/4 + 2*f(n/8)) * f(n) = 3*c*n + 8*f(n/8) * f(n) = k*c*n + 2^k*f(n/2^k) * Stop when k = log_n (or 2^k = n) * f(n) is in O(nlog_2n + n) is in O(nlog_2n) * f(n) = c + 2*f(n-1) * O(2^n) Sorting: Given a collection of values, put the collection "in order" * What kinds of things do we sort? * Lists, Vectors, Arrays * Two perspectives on the result: * In-place: You modify the input collection * "Out-of-place": You do not modify the input collection, instead you return a new sorted version * Two "costs" associated with most sorting algorithms * Running time * Memory * We're going to look at different sorting algorithms (in Java) * We'll also analyze them * Learned in 151: * Quicksort: Split into large and small elements, sort each half, shove 'em together * Mergesort: Split into two halves, sort the two halves, MERGE 'em together. * Bubblesort (EVIL) * Insertion Sort: Think of your structure as having two parts. Repeatedly take one from the second part and INSERT it into the "correct" place in the first part. * Selection Sort: Repeatedly SELECT the smallest remaining element and swap it into the correct place. * New ones to study * Bucket sort * Heap sort (later this semester) * Radix sort How should we express sorting in Java? * What are the parameters to sort? * The collection you want to sort (list, Vector, array) * The "comparison operation" used to determine the order * How do we express the comparison operation in Java terms? * Vector mystuff = ...; * sort(mystuff, (lambda (thing1 thing2) (string-<=? thing1.lname thing2.lname))) * Have some global table of all posible comparison operations and represent the comparison operations by their number in the table. * What can you pass as parameters? * Basic values (e.g., ints, characters) * Classes? (No.) * Methods? (No.) * Objects (yes!) * We need to figure out how to use objects to represent procedures * Traditional mechanism: Comparator Interface * Version 1: Every comparator provides a mayPrecede operation * Version 2: Built-In Comparator interface specifies compare(Object,Object), which returns an integer * Where should sort() appear? * Possiblity one: A single SortingAlgorithms class * Each sort is a static method * Possibility two: A Sorter interface with a sort() method * Every new sorting algorithm falls in a class that implements Sorter