What are the different ways to do sorting in java

This question was asked in an interview. Except Collections.sort () what other methods.

+4
source share
5 answers

Sorting interfaces

Comparable<T> and Comparator<T> are the standard interfaces used by all standard Java sorting options (all except those related to primitive arrays).

In Java-talk, any class that implements Comparable has a "natural order". (Technically, he should implement Comparable<? super E> , where E matches itself, to have a natural order). Classes that do not have a natural order can be sorted using an external comparator. The comparator can also be used to implement a sort order that runs against the natural order (for example, sorting strings in descending alphabetical order).

These principles apply to both SortedSet<E> and SortedMap<K,V> , which sort their elements / keys automatically, using either the natural order or the supplied comparator.

The same principles can also be found in the static methods of the Utility.

which can be used to sort arrays and lists, respectively, each of which does not support sorting.


guavas

The Guava library takes this a bit further by providing abstract Ordering as a basic Comparator implementation that already contains standard methods, such as providing a reverse view of yourself and many convenient methods for sorting and retrieving based on this Ordering .


Link

A good article on Ordering Objects can be found in the Sun Java Trail Collection Tutorial .

+7
source
  • SortedSet or SortedMap if the keys are unique.
  • PriorityQueue.
  • Arrays.sort ().
  • Native code.
  • JDBC query with ORDER BY clause.
  • LDAP search with indexed attribute.

I am sure there are more of them.

+3
source
  • The Sort insert is used for small arrays.
  • Double Pivot Quick Sort is used for larger arrays.
  • MergeSort is used to sort an object.
+2
source

Arrays.sort(..) or do the sorting yourself.

+1
source

You can paste your data into a SortedSet (e.g. TreeSet ) and pull it out again in sorted order by going through an iterator. This is not a general sorting method (since it does not allow duplicate entries), but will work for a fairly large dataset.

0
source

All Articles