Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

arrays
sort
method
java
function

How to use the Arrays.sort() method in Java

Educative Answers Team

The built-in java.util.Arrays class has a method called sort() which can be used to sort an array in-place.

Syntax

svg viewer

If starting_index and ending_index are not specified, the whole array is sorted.

Code

The following code snippet demonstrates how Arrays.sort() can be used to sort an integer array:

import java.util.Arrays; 

class Program {
    public static void main( String args[] ) {
        int [] arr = {5, -2, 23, 7, 87, -42, 509};
        System.out.println("The original array is: ");
        for (int num: arr) {
          System.out.print(num + " ");
        }
        Arrays.sort(arr);
        System.out.println("\nThe sorted array is: ");
        for (int num: arr) {
          System.out.print(num + " ");
        }
    }
}

The code snippet below uses the optional starting and ending indexes to sort the array within the specified bounds only:

import java.util.Arrays; 

class Program {
    public static void main( String args[] ) {
        int [] arr = {5, -2, 23, 7, 87, -42, 509};
        System.out.println("The original array is: ");
        for (int num: arr) {
          System.out.print(num + " ");
        }
        Arrays.sort(arr, 3, 6);
        System.out.println("\nThe sorted array (from position 3 to 6) is: ");
        for (int num: arr) {
          System.out.print(num + " ");
        }
    }
}

RELATED TAGS

arrays
sort
method
java
function
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring