Sorting

The Arrays class in Java, located in the java.util package, provides utility methods for working with arrays. It offers various static methods to perform operations such as sorting, searching, comparing, and filling arrays. Here’s an overview of the Arrays class, its syntax, and examples demonstrating its usage.

Method Signature Description
public static void sort(int[] a) Sorts the int array in ascending numerical order.
public static void sort(long[] a) Sorts the long array in ascending order.
public static void sort(double[] a) Sorts the double array in ascending order.
public static void sort(char[] a) Sorts the char array in ascending Unicode order.
public static void sort(byte[] a) Sorts the byte array in ascending order.
public static void sort(short[] a) Sorts the short array in ascending order.
public static void sort(float[] a) Sorts the float array in ascending order.
public static <T extends Comparable<? super T>> void sort(T[] a) Sorts an object array into ascending order using natural ordering.
public static <T> void sort(T[] a, Comparator<? super T> c) Sorts an object array using a custom comparator.
public static void sort(int[] a, int fromIndex, int toIndex) Sorts a range within an int array.
public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) Sorts a subrange of an object array with a comparator.
public static void parallelSort(int[] a) Parallel sort of int array for better performance on large datasets.
public static void parallelSort(long[] a) Parallel sort for long arrays.
public static <T extends Comparable<? super T>> void parallelSort(T[] a) Parallel sort for object arrays using natural ordering.
public static <T> void parallelSort(T[] a, Comparator<? super T> cmp) Parallel sort for object arrays using a custom comparator.
public static void parallelSort(int[] a, int fromIndex, int toIndex) Parallel sort for a range of int array.
public static <T> void parallelSort(T[] a, int fromIndex, int toIndex, Comparator<? super T> cmp) Parallel sort for a range in an object array using comparator.
import java.util.Arrays;
public class ArraysSortingExample {
    public static void main(String[] args) {
        String[] students = {"Paani", "Mahesh", "Datta", "Ganesh", "Harsha"};

        System.out.println("Before sorting: " + Arrays.toString(students));

        // Sorting the array using Arrays.sort()
        Arrays.sort(students);

        System.out.println("After sorting: " + Arrays.toString(students));
    }
}

/*
D:\> ArraysSortingExample.java

D:\>java ArraysSortingExample
Before sorting: [Paani, Mahesh, Datta, Ganesh, Harsha]
After sorting: [Datta, Ganesh, Harsha, Mahesh, Paani]
*/
Scroll to Top