开发者

What are the different ways of performing sorting in java

This question was asked in an intervie开发者_开发百科w . Except Collections.sort() what are the other methods .


Sorting Interfaces

Comparable<T> and Comparator<T> 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<E> and SortedMap<K,V> 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.


Guava

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.


  1. SortedSet or SortedMap, provided the keys are unique.
  2. PriorityQueue.
  3. Arrays.sort().
  4. Own code.
  5. A JDBC query with an ORDER BY clause.
  6. An LDAP search against an indexed attribute.

I'm sure there are more.


  1. Insertion Sort is used for small size arrays.
  2. Dual Pivot Quick Sort is used for larger size arrays.
  3. MergeSort is used for sorting object.


Arrays.sort(..), or implement sorting yourself.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜