swati singhvi
swati singhvi

Reputation: 31

What are the different ways of performing sorting in java

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

Upvotes: 3

Views: 1241

Answers (5)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299218

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

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.

Upvotes: 7

user207421
user207421

Reputation: 311052

  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.

Upvotes: 4

Alexander Torstling
Alexander Torstling

Reputation: 18908

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.

Upvotes: 0

Dead Programmer
Dead Programmer

Reputation: 12585

  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.

Upvotes: 2

Bozho
Bozho

Reputation: 597422

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

Upvotes: 1

Related Questions