sort1 - Robert Sedgewick and Kevin Wayne Copyright 2005

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Robert Sedgewick and Kevin Wayne Copyright 2005 http://www.Princeton.EDU/~cos226 3.1 Elementary Sorts Reference: Chapter 6, Algorithms in Java, 3 rd Edition, Robert Sedgewick. 2 Basic Terms Ex: student record in a University. Sort: rearrange sequence of objects into ascending order. 3 Rules of the Game Goal. Write robust sorting library that can sort any type of data into sorted order using the data type's natural order. Callbacks. ! Client passes array of objects to sorting routine. ! Sorting routine calls back object's comparison function as needed. Implementing callbacks. ! Java: interfaces . ! C: function pointers. ! C++: functors. ! C#: delegates. ! Lisp: first class functions. client data type sorting library construct callbacks compare sort 4 Comparable Interface Comparable interface. Require a method so that v.compareTo(w) returns: ! A negative integer if v is less than w . ! A positive integer if v is greater than w . ! Zero if v is equal to w . Consistency. It is the programmer's responsibility to ensure that compareTo() specifies a total order. ! Transitivity: if a < b and b < c, then a < c. ! Trichotomy: either (i) a < b or (ii) b < a or (iii) a = b. Built-in comparable types. String , Double , Integer , Date , File . User-defined comparable types. Implement the Comparable interface. 5 Implementing the Comparable Interface: Date public class Date implements Comparable < Date > { private int month , day , year ; public Date ( int m , int d , int y ) { month = m ; day = d ; year = y ; } public int compareTo ( Date b ) { Date a = this ; if ( a . year < b . year ) return - 1 ; if ( a . year > b . year...
View Full Document

This document was uploaded on 06/10/2011.

Page1 / 7

sort1 - Robert Sedgewick and Kevin Wayne Copyright 2005

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online