Java Utility Library

Java Arrays - sort() Method



The java.util.Arrays.sort() method is used to sort the specified range of the array into ascending order. The range to be sorted starts from the index fromIndex (inclusive) and ends at index toIndex (exclusive). If fromIndex and toIndex are equal then the range to be sorted is empty.

Syntax

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

Parameters

a Specify the array to be sorted.
fromIndex Specify the index of the first element (inclusive) to be sorted.
toIndex Specify the index of the last element (exclusive) to be sorted.

Return Value

void type.

Exception

  • Throws IllegalArgumentException, if fromIndex > toIndex.
  • Throws ArrayIndexOutOfBoundsException, if fromIndex < 0 or toIndex > a.length.

Example:

In the example below, the java.util.Arrays.sort() method is used to sort a specified range of a float array.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating an unsorted float array
    float MyArr[] = {10f, 2f, -3f, 35f, 56f, 15f, 47f};

    //printing array before sorting
    System.out.print("MyArr contains:"); 
    for(float i: MyArr)
      System.out.print(" " + i);

    //sort the array
    Arrays.sort(MyArr, 2, 7);

    //printing array after sorting
    System.out.print("\nMyArr contains:"); 
    for(float i: MyArr)
      System.out.print(" " + i);   
  }
}

The output of the above code will be:

MyArr contains: 10.0 2.0 -3.0 35.0 56.0 15.0 47.0
MyArr contains: 10.0 2.0 -3.0 15.0 35.0 47.0 56.0

❮ Java.util - Arrays