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.
This
preview
has intentionally blurred sections.
Sign up to view the full version.
5
Implementing the Comparable Interface: Date
public class
Date
implements
Comparable
<
Date
>
{
private int
month
,
day
,
year
;
public

This is the end of the preview.
Sign up
to
access the rest of the document.
- Spring '09
- Algorithms, Data Structures, Sort, Bubble Sort, Insertion Sort, Selection Sort, Comparison sort, Robert Sedgewick
-
Click to edit the document details