This question was asked in an interview . Except Collections.sort() what are the other methods .
- Insertion Sort is used for small size arrays.
- Dual Pivot Quick Sort is used for larger size arrays.
- MergeSort is used for sorting object.
You can stick your data into a SortedSet
(e.g. TreeSet
) and pull it out again in sorted order by traversing with an iterator. This is not really a general sorting method (since it doesn't allow duplicated entries), but would work for quite a lot of data set.
Comparable and Comparator are the standard interfaces used by all standard Java sorting options (all except those on primitive arrays, that is).
In Java-speak, any Class that implements Comparable has a "natural order". (Technically, it must implement Comparable<? super E>
where E matches itself, to have a natural order). Classes that don't have a natural order can be sorted using an external Comparator. A Comparator can also be used to implement a sort order that runs against the natural order (e.g. sort Strings in descending alphabetic order).
These principles are applied both in the SortedSet and SortedMap implementations, that sort their elements / keys automatically using either the natural order or a supplied comparator.
These same principles can also be found in the static Utility methods
- Arrays.sort(arr) and Arrays.sort(arr, comparator) for Arrays
- Collections.sort(list) and Collections.sort(list, comparator) for Lists
that can be used to sort arrays and lists, respectively, each of which don't support sorting themselves.
The Guava Library takes this a bit further by providing the abstract Ordering class as base implementation of Comparator which already contains standard methods like providing a reverse view of itself and many convenience methods for sorting and retrieving based on this Ordering.
Reference
A good article about Object Ordering can be found in the Sun Java Tutorial's Collection Trail.
- SortedSet or SortedMap, provided the keys are unique.
- PriorityQueue.
- Arrays.sort().
- Own code.
- A JDBC query with an ORDER BY clause.
- An LDAP search against an indexed attribute.
I'm sure there are more.