Contents    Page-10    Prev    Next    Page+10    Index   

Sorting in Java Library

Java provides generic sort methods for lists and arrays:

void sort( Object [] arr )

void Collections.sort( List list )

void sort( Object [] arr, Comparator c )

void Collections.sort( List list, Comparator c )

The first methods use the natural compareTo method, while the second allow a Comparator to be specified. The sort algorithm is a modified mergesort, stable and guaranteed O(n · log(n)).

Since the Collection interface provides a toArray method, it is easy to sort any Collection by first converting it to an array.

The Java List class provides sort methods that operate by dumping the List into an array, sorting the array, and then resetting the List elements in the sorted order.