Way2Java

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

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));
  }
}



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.