Arrays.sort() in Java with examples

In Java, an array is a class that has methods like sort, insertion, comparison, search. The sort method is one of them. Sort() method sorts integers. We can apply the sort() method in two forms:

  1. sort() method with no parameter. In this, we can sort the complete array.  Syntax: Arrays.sort()
  2. sort(int[] array_name , int index_from, int index_to). This method accepts three parameters – the first one is an array, the second one is the index from which we want to sort an array, and the third is the index up to which we want to sort that array.

This sort() method does not return anything. It will sort integers and then we can use print statements for printing sorted integers.

One thing to remember is that we have to use ‘Arrays’ before using the sort() method because the sort() method is coming from Arrays class. Without Arrays, Java cannot determine where is this sort() method coming from?

Algorithm:

  1. Create a class.
  2. create a main method inside the same class.
  3. create an integer array and assign some values inside that array.
  4. Arrays.sort(array_name) – now this line will sort complete array.
  5. With the help of print statements, we can print that array.

import Array class from the java.util package

import java.util.Arrays;

 

Create a class and main method

public class ArraySortExample{
    public static void main(String[] args){
        
    }
}

Inside the main method, create an array of integer data type and apply the sort method.

public static void main(String[] args){
    int[] roll_numbers = {12,4,5,10,7,2,11,20};
    Arrays.sort(roll_numbers);
    System.out.println(roll_numbers);
}

the output:

[2,4,5,7,10,11,12,20]

On the other hand, parameterized sort method would be:

public static void main(String[] args){
    int[] roll_numbers = {12,4,5,20,11,7,2,10};
    System.out.println(Arrays.sort(roll_numbers,0,5);
}

It will print:

[4,5,7,11,12,20]

That’s all for this tutorial. Thank you.

Also read: Heap Sort for decreasing order using min heap in Java

Leave a Reply

Your email address will not be published.