Lesson: Algorithms
The polymorphic algorithms described here are pieces of reusable functionality provided by the Java platform. All of them come from the Collections
class, and all take the form of static methods whose first argument is the collection on which the operation is to be performed. The great majority of the algorithms provided by the Java platform operate on List
instances, but a few of them operate on arbitrary Collection
instances. This section briefly describes the following algorithms:
Sorting
The sort
algorithm reorders a List
so that its elements are in ascending order according to an ordering relationship. Two forms of the operation are provided. The simple form takes a List
and sorts it according to its elements' natural ordering. If you're unfamiliar with the concept of natural ordering, read the Object Ordering section.
The sort
operation uses a slightly optimized merge sort algorithm that is fast and stable:
- Fast: It is guaranteed to run in
n log(n)
time and runs substantially faster on nearly sorted lists. Empirical tests showed it to be as fast as a highly optimized quicksort. A quicksort is generally considered to be faster than a merge sort but isn't stable and doesn't guaranteen log(n)
performance. - Stable: It doesn't reorder equal elements. This is important if you sort the same list repeatedly on different attributes. If a user of a mail program sorts the inbox by mailing date and then sorts it by sender, the user naturally expects that the now-contiguous list of messages from a given sender will (still) be sorted by mailing date. This is guaranteed only if the second sort was stable.
http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html