Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
sort
array
arrayutils
communitycreator

What is ArrayUtils.isSorted(int[] array) in Java?

abhilash

isSorted(int[] array) is a static method of the ArrayUtils class that checks whether the array is sorted in natural order.

Examples

Example 1

  • Array: [1, 2, 3, 4, 5]

Application of the isSorted (int[] array) function will result in true because the array is sorted in the natural order for integers i.e., ascending order.

Example 2

  • Array: [false, false, true, true, true]

Application of the isSorted (int[] array) function will result in true because the array is sorted in the natural order for Booleans i.e., all false values come first followed by the true values.


ArrayUtils is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven Project by adding the following dependency to the pom.xml file.

<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
</dependency>

For other versions of the commons-lang package, refer to the Maven Repository.

You can import the ArrayUtils class as follows.

import org.apache.commons.lang3.ArrayUtils;

Syntax

public static boolean isSorted(int[] array)

Parameters

  • int[] array: array to check if it is sorted.

Return value

The function returns true if the array is sorted. Otherwise, it returns false.

Code

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        int[] array1 = {1,2,3,4,5};
        boolean[] array2 = {false, false,true, true,true};
        System.out.println("array1 is sorted in natural ordering - " + ArrayUtils.isSorted(array1));
        System.out.println("array2 is sorted in natural ordering - " + ArrayUtils.isSorted(array2));
    }
}

Expected output

array1 is sorted in natural ordering - true
array2 is sorted in natural ordering - true

RELATED TAGS

java
sort
array
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring