Java.util.Arrays.sort() Method

Advertisements


Description

The java.util.Arrays.sort(short[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of shorts into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.

Declaration

Following is the declaration for java.util.Arrays.sort() method

public static void sort(short[] a, int fromIndex, int toIndex)

Parameters

  • a -- This is the array to be sorted.

  • fromIndex -- This is the index of the first element (inclusive) to be sorted.

  • toIndex -- This is the index of the last element (exclusive) to be sorted .

Return Value

This method does not return any value.

Exception

  • IllegalArgumentException -- if fromIndex > toIndex

  • ArrayIndexOutOfBoundsException -- if fromIndex < 0 or toIndex > a.length

Example

The following example shows the usage of java.util.Arrays.sort() method.

package com.tutorialspoint;

import java.util.Arrays;

public class ArrayDemo {

   public static void main(String[] args) {

    // initializing unsorted short array
    short sArr[] = {3, 13, 1, 9, 21};

    // let us print all the elements available in list
    for (short number : sArr) {
      System.out.println("Number = " + number);
    }
	
    // sorting array from index 1 to 4
    Arrays.sort(sArr, 1, 4);

    // let us print all the elements available in list
    System.out.println("short array with some sorted values(1 to 4) is:");
    for (short number : sArr) {
      System.out.println("Number = " + number);
    }
  }
}

Let us compile and run the above program, this will produce the following result:

Number = 3
Number = 13
Number = 1
Number = 9
Number = 21
short array with some sorted values(1 to 4) is:
Number = 3
Number = 1
Number = 9
Number = 13
Number = 21



Advertisements
Advertisements