Sorting complete array elements sort()

Sorting complete array elements sort()

Arrays.sort() method sorts all the array elements in ascending order. It avoids writing tedious sorting algorithms.

Two methods exist with Array class for sorting. 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.
Example on Sorting complete array elements sort() uses both the above methods.


Sorting complete array elements sort()
Ouutput screen of Sorting complete array elements sort()

int numbers[] = { 90, 10, 50, 60, 30, 40, 20, 80, 70 };
System.out.println(“Before sort numbers: ” + Arrays.toString(numbers));

An integer array object numbers is created and elements are printed using toString() method of Arrays class.

Arrays.sort(numbers);
System.out.println(“After sort numbers: ” + Arrays.toString(numbers));

The sort() method of Arrays class sorts the elements of numbers object into ascending order and the sorted elements are printed with Arrays.toString() method.

int numbers1[] = { 9, 1, 5, 6, 3, 4, 2, 8, 7 };

Another integer array object numbers1 is created with a few elements. The earlier sort() method sorts all the elements of the array. The sort() method is overloaded that sorts a few elements of the array.

Arrays.sort(numbers1, 2, 7);

The above sort() method sorts the numbers1 elements starting from 2nd element to 6th (7-1) in ascending order. Remaining elements of numbers1 are not sorted and they remain as it is. Observe the screenshot.

A similar program exists with Collections.sort() that sorts data structure elements.

The Arrays class from java.util package does not have copy() method to copy the elements of one array to another as arraycopy() method already exists with general arrays.

Leave a Reply

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