Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Arrays.sort() in Java with examples

  • Difficulty Level : Easy
  • Last Updated : 15 Oct, 2021

An array class is a class containing static methods that are used with arrays in order to search, sort, compare, inserting elements, or returning a string representation of an array. in an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows been present in java.util.Arrays class. Here we will be discussing out different plots using the sort() method of the Arrays class.

Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Syntax: sort() Method 

Arrays.sort(); 

Syntax: Overloaded sort() Method



public static void sort(int[] arr, int from_Index, int to_Index) ;

Parameters: It takes three parameters as can be perceived from the syntax which is as follows:

  • The array to be sorted
  • The index of the first element, inclusive, to be sorted (Referred to as from_index)
  • The index of the last element, exclusive, to be sorted (Referred to as last_index)

Return Type: It does not return any value.

Now let us see the implementation of the sort() function across different scenarios of the Arrays class as follows:

Example 1:

Java




// Java Program to Sort Array of Integers
// by Default Sorts in an Ascending Order
// using Arrays.sort() Method
  
// Importing Arrays class from the utility class
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
  
        // Applying sort() method over to above array
        // by passing the array as an argument
        Arrays.sort(arr);
  
        // Printing the array after sorting
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

 Output:  

Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]

Example 2:

Java






// Java program to Sort a Subarray in Array
// Using Arrays.sort() method
  
// Importing Arrays class from java.util package
import java.util.Arrays;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        // It contains 8 elements as follows
        int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
  
        // Sort subarray from index 1 to 4, i.e.,
        // only sort subarray {7, 6, 45, 21} and
        // keep other elements as it is.
        Arrays.sort(arr, 1, 5);
  
        // Printing the updated array which is
        // sorted after 2 index inclusive till 5th index
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

 Output:  

Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]

Example 3:

Java




// Java program to Sort a Subarray in Descending order
// Using Arrays.sort()
  
// Importing Collections class and arrays classes
// from java.util package
import java.util.Arrays;
import java.util.Collections;
  
// Main class
public class GFG {
    
    // Main driver method
    public static void main(String[] args)
    {
        // Note that we have Integer here instead of
        // int[] as Collections.reverseOrder doesn't
        // work for primitive types.
        Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
  
        // Sorts arr[] in descending order using
        // reverseOrder() method of Collections class
        // in Array.sort() as an argument to it
        Arrays.sort(arr, Collections.reverseOrder());
  
        // Printing the array as generated above
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

 Output: 

Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]

Example 4:

Java




// Java program to sort an array of strings
// in ascending and descending alphabetical order
// Using Arrays.sort()
  
// Importing arrays and Collections class
// from java.util class
import java.util.Arrays;
import java.util.Collections;
  
// Main class
public class GFG {
    
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String arr[] = { "practice.geeksforgeeks.org",
                         "quiz.geeksforgeeks.org",
                         "code.geeksforgeeks.org" };
  
        // Sorts arr[] in ascending order
        Arrays.sort(arr);
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
  
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
  
        // Lastly printing the above array
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
    }
}

Output: 

Modified arr[] : 


Modified arr[] : 
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]

Now lastly we will be implementing the sort() method to the fullest because here we will be declaring our own defined criteria with the help of the Comparator interface.

Example 5:

Java




// Java program to demonstrate Working of 
// Comparator interface
  
// Importing required classes
import java.io.*;
import java.lang.*;
import java.util.*;
  
// Class 1
// A class to represent a student.
class Student {
    int rollno;
    String name, address;
  
    // Constructor
    public Student(int rollno, String name, String address)
    {
        // This keyword refers to current object itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
  
    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
  
// Class 2
// Helper class extending Compatator interface
class Sortbyroll implements Comparator<Student> {
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}
  
// Class 3
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        Student[] arr
            = { new Student(111, "bbbb", "london"),
                new Student(131, "aaaa", "nyc"),
                new Student(121, "cccc", "jaipur") };
  
        System.out.println("Unsorted");
  
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
  
        // Sorting on basic as per class 1 created
        // (user-defined)
        Arrays.sort(arr, new Sortbyroll());
  
        System.out.println("\nSorted by rollno");
  
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }
}

 Output: 

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc

Note: There is a slight difference between Arrays.sort() vs Collections.sort(). Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayList, LinkedList, etc. 

This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!