{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

sort1 - B asic T e r m s 3.1 E le m e n t a r y S o r t s...

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

View Full Document Right Arrow Icon
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.
Background image of page 1

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

View Full Document Right Arrow Icon
5 Implementing the Comparable Interface: Date public class Date implements Comparable < Date > { private int month , day , year ; public
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}