Sorting array elements sort() Comparator

Sorting array elements sort() Comparator

The earlier sort() example sorts implicitly in natural ascending order. The order can be customized with the overloaded sort() method that takes a Comparator object as parameter.

Two methods exist for sorting array elements with Arrays class. Following are the method signatures.

  1. static void sort(int array1[]): Sorts all the elements of the array array1 in ascending numerical order. The sorting algorithm used is Quicksort (Mergesort) with Collections.sort()). The sort(int array1[]) method is overloaded taking arrays of different data types like long array, short array, char array, byte array, double array, float array and Object array as parameter. That is, the sort() method is capable to sort an array with any data type or objects.
  2. static void sort(int aray1[], int startIndex, int endIndex): This is a modified form of the previous sort() method useful to sort a few elements of the array (not all elements). The elements falling from startIndex to endIndex-1 are sorted. This method is overloaded to accept any type of array. Two exceptions thrown by this method are IllegalArgumentException when startIndex is greater than endIndex and ArrayIndexOutOfBoundsException when the index numbers are out of range.

First method is illustrated in "Sorting array elements with sort()".

Second method (on Sorting array elements sort() Comparator) is discussed in the next link.

Regarding Comparator and its usage, many examples are given as in interface Comparator, Comparator Example and Comparable vs Comparator.

Leave a Reply

Your email address will not be published. Required fields are marked *