Java Reference
In-Depth Information
ȗ Transitive: If
a.compareTo(b)
ʎ 0 and
b.compareTo(c)
ʎ 0, then
a.compareTo(c)
ʎ 0
Once your
Coin
class implements the
Comparable
interface, you can simply pass
an array of coins to the
Arrays. sort
method:
Coin[] coins = new Coin[n];
// Add coins
. . .
Arrays.sort(coins);
If the coins are stored in an
ArrayList
, use the
Collections.sort
method
instead; it uses the merge sort algorithm:
The
Collections
class contains a sort method that can sort array lists.
ArrayList<Coin> coins = new ArrayList<Coin>();
// Add coins
. . .
Collections. sort (coins);
As a practical matter, you should use the sorting and searching methods in the
Arrays
and
Collections
classes and not those that you write yourself. The
library algorithms have been fully debugged and optimized. Thus, the primary
purpose of
this chapter was not to teach you how to implement practical sorting and
searching
algorithms. Instead, you have learned something more important, namely
that different algorithms can vary widely in performance, and that it is worthwhile to
learn more about the design and analysis of algorithms.
655
656
S
ELF
C
HECK
16.
Why can't the
Arrays.sort
method sort an array of
Rectangle
objects?
17.
What steps would you need to take to sort an array of
BankAccount
objects by increasing balance?