Tuesday, 17 May 2011

Sorting an array in java

For sorting Arrays.sort(arr) is used, which is static function in arrays class.

Here a is array and method uses a tuned version of the QuickSort algorithm

int arr[] = {4,3,1};
Arrays.sort(arr);



This will sort the array in ascending order.


Seeing various sorting methods:


 

























Method
Arrays sort methods


Description


Arrays.sort(pa);

 


Sorts the elements of the array of a primitive type into ascending order using their natural ordering.


Arrays.sort(pa, from, to);


Sorts the elements pa[from]...pa[to-1] of a primitive type. into ascending order.


Arrays.sort(oa);


Sorts the elements of the array of an object type into ascending order, using the order defined by Comparable interface, which defines the compareTo method. Note that many Java classes such as String (but not StringBuffer), Double, BigInteger, etc implement Comparable.


Arrays.sort(oa, from, to);


Sorts the elements of the array, in the range from...to of an object type into ascending order.


Arrays.sort(oa, comp);


Sorts the elements of the array of an object type into ascending order, using the Comparator comp.


Arrays.sort(oa, from, to, comp);


Sorts the elements of the array, in the range from...to of an object type into ascending order using the Comparator comp.

No comments:

Post a Comment