Sorting algorithms are
based on
the following operations:
Comparing2 items
Exchange2 items
The primitive operation in
sorting algorithm is the
compare operation
Comparing items: the
Java
Comparable interface
Sortingrequires
that 2 items can be
compared.
Java defines the
Comparable<T>
interface
to
represent
this requirement:
public Interface Comparable<T>
{
public int compareTo(T o);
}
Classes that
implement the
Comparable<T>
interface
are
comparable classes
Requirements of the
compareTo( ) method:
a.compareTo(b) returns a negative value if a is less than b
a.compareTo(b) returns zero (0) if a is equal to b
a.compareTo(b) returns a positive value if a is greater than b
Previously,
we have
implemented the
Comparable<T>
interface
in the
Circle class:
Exchanging 2 items (objects)
Review:exchanging the
content of
2 variables:
Method to
exchange (= swap)array elementsa[i] and
a[j]:
private static void exch( DataType[] a, int i, int j )
{
DataType help;
help = a[i];
a[i] = a[j];
a[j] = help;
}
DEMO:
demo/14-sort/01-exchange/Demo.java
Defining a generic (parameterize)
exch( ) method
This exch( ) Method
will only work on
objects of the
typeDataType:
(Demo2.java)
private static void exch( DataType[] a, int i, int j )
{
DataType help;
help = a[i];
a[i] = a[j];
a[j] = help;
}
To define a generic (parameterized)exch( ), we
use the followingsyntax:
private static <T> void exch( T [] a, int i, int j )
{
T help;
help = a[i];
a[i] = a[j];
a[j] = help;
}