Sort part array elements sort()


On sorting of array elements, three important and often used methods exist with Array class. They are discussed in this tutorial "Sort part array elements sort()" in easy terms, example and screenshot.

  1. Sorting array elements with sort()
  2. Sorting array elements with sort() and Comparator
  3. Sorting few array elements with sort()

After seeing the first two let us go to the third one where few elements of the array are sorted (not all elements).

Following is the method signature

  • 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 between 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 Sort part array elements sort()
import java.util.Arrays;
public class SortingFewElements
{
  public static void main(String args[])
  {
    String names[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
    System.out.println("Before sorting: " +  Arrays.toString(names));

    Arrays.sort(names, 2, 5);
    System.out.println("After sorting: " + Arrays.toString(names));
  }
}


Sort part array elements sort()
Output screenshort on Sort part array elements sort()

System.out.println(“Before sorting: ” + Arrays.toString(names));

A string array, names, is created and its elements are printed with toString() method of Arrays class. Usage of toString() method is the easiest way of printing an array elements without using for loop.

Arrays.sort(names, 2, 5);

The sort() is method in the Arrays class is overloaded. Here, the method takes three parameters of the name of the array and the elements to be sorted. In the above statement, from 2nd element to 5-1 element are sorted; that is, 2, 3 and 4 elements are sorted in the ascending order and the remaining are untouched. Observe the screenshot.

Leave a Comment

Your email address will not be published.