Arrays.sort() in Java (original) (raw)
Last Updated : 08 Apr, 2025
The **Arrays.sort() method is used for sorting the elements in an Array. It has two main variations:
- Sorting the entire array (it may be an integer or character array)
- Sorting a specific range by passing the starting and ending indices.
Below is a simple example that uses the sort() method to arrange an array of integers in ascending order.
Java `
// Java Program to Implement sort() import java.util.Arrays;
class Geeks { public static void main(String args[]) {
// Integer Array
int[] a = { 2, -1, 3, 4 };
// Character Array
char[] b = { 'b', 'a', 'c', 'b' };
// Sort both arrays
Arrays.sort(a);
Arrays.sort(b);
// Print sorted integer array
System.out.print("");
for (int n : a) {
System.out.print(n + " ");
}
// Print sorted character array
System.out.print("\n");
for (char c : b) {
System.out.print(c + " ");
}
}
}
`
**Explanation: In this example, we sort the integer array and a character array using Arrays.sort(). Then it prints both arrays in ascending order. The character “b” repeats in the output because it appears twice in the original array. Sorting does not remove duplicates, it only reorders elements.
**Note: When we sorting an array of primitive types, Arrays.sort() does not allow us to provide a custom comparator. We can sort primitive types in natural order or increasing order, or non-decreasing order.
Table of Content
- Syntax of Arrays.sort() Method
- Sorting Subarrays
- Descending Order Sorting – Using the Reverse Order
- Custom Sorting with Comparator
- Natural Sorting with Comparable Interface
Syntax of Arrays.sort() Method
**1. sort() Method
Arrays.sort();
**2. Overloaded sort() Method
public static void sort(int[] arr, int from_Index, int to_Index) ;
**Parameters:
- **arr: The array to be sorted.
- **from_Index: The index of the first element (inclusive) to be sorted.
- **to_Index: The index of the last element (exclusive) to be sorted.
**Return Type: void (This method does not return anything).
Sorting Subarrays
We have to specify a range of indices by leaving other elements of the array unchanged.
Java `
// Java program to Sort a Subarray import java.util.Arrays;
public class Geeks { public static void main(String[] args){
int[] a = { 2, -1, 4, 3};
// Sort subarray from index 1 to 3 inclusively
Arrays.sort(a, 1, 4);
System.out.println(Arrays.toString(a));
}
}
`
**Explanation: This example sort the elements at indices 1, 2, and 3 (-1, 4, 3) and does not change the index 0 element (2).
Descending Order Sorting – Using the Reverse Order
To sort an array in descending order, we can use Arrays.sort() method with Collections.reverseOrder() as a comparator.
Java `
// Java program to Sort an array in Descending order import java.util.Arrays; import java.util.Collections;
public class Geeks {
public static void main(String[] args){
Integer[] a = { 2, -1, 3, 4};
// Sort the array in descending order using
// reverseOrder() method of Collections class
Arrays.sort(a, Collections.reverseOrder());
System.out.println(Arrays.toString(a));
}
}
`
**Explanation: This sorting works on an Integer[] array, not int[]. Because, the Collections.reverseOrder() requires objects that implement Comparable. Primitives like int don’t, but their wrapper class Integer does.
String Array Sorting – Descending Alphabetical Order
To sort an array of strings in descending alphabetical order, the Arrays.sort() method combined with Collections.reverseOrder() method and it arranges the strings from Z to A based on lexicographical order.
Java `
// Java program to sort an array of strings // in descending alphabetical order import java.util.Arrays; import java.util.Collections;
public class Geeks {
public static void main(String[] args){
// Custom input string
String a[] = { "practice.geeksforgeeks.org",
"www.geeksforgeeks.org",
"code.geeksforgeeks.org" };
// Sorts array in descending order
Arrays.sort(a, Collections.reverseOrder());
System.out.println(Arrays.toString(a));
}
}
`
Output
[www.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]
Custom Sorting with Comparator
We can sort an array of objects by defining custom sorting logic with the help of using the Comparator interface.
Java `
// Java program to sort an array // using custom comparator import java.io.; import java.lang.; import java.util.*;
class Student { int r; String n, a;
// Constructor
public Student(int r, String n, String a)
{
// This keyword refers to current object itself
this.r = r;
this.n = n;
this.a = a;
}
// toString() method to print student details in main()
public String toString()
{
return this.r + " " + this.n + " "
+ this.a;
}
}
// Helper class extending Comparator interface class Sortbyroll implements Comparator {
// Used for sorting in ascending order of
// roll number
public int compare(Student x, Student y){
return x.r - y.r;
}
}
class Geeks { public static void main(String[] args){ Student[] x = { new Student(1, "Ram", "MP"), new Student(2, "Shyam", "UP"), new Student(3, "Hari", "Delhi") };
// Sorting on basic as per class 1 created
// (user-defined)
Arrays.sort(x, new Sortbyroll());
for (int i = 0; i < x.length; i++)
System.out.println(x[i]);
}
}
`
Output
1 Ram MP 2 Shyam UP 3 Hari Delhi
**Explanation:
- In this example, the students are sorted based on their **roll number in ascending order, as specified by the **compare() method in the **Sortbyroll class.
- Here, we use a custom comparator to sort the Student objects by their roll number, as the Student class does not implement the Comparable interface for sorting by roll number.
- This allows custom sorting without modifying the class itself.
Natural Sorting with Comparable Interface
In the below example, we sort an array of Student objects based on their name alphabetically.
Java `
// Java program to sort an array of Student objects // using Comparable import java.util.Arrays;
class Student implements Comparable { int r; String n; String a;
// Constructor
public Student(int r, String n, String a) {
this.r = r;
this.n = n;
this.a = a;
}
// compareTo method to sort by name
public int compareTo(Student o) {
return this.n.compareTo(o.n);
}
// toString() method to print Student details
public String toString() {
return this.r + " " + this.n + " " + this.a;
}
}
public class Geeks { public static void main(String[] args) { Student[] s = { new Student(1, "Ram", "UP"), new Student(2, "Shyam", "MP"), new Student(3, "Hari", "Bihar") };
// Sorting students by name in alphabetical order
Arrays.sort(s);
for (Student student : s)
System.out.println(student);
}
}
`
Output
3 Hari Bihar 1 Ram UP 2 Shyam MP
**Explanation:
- In this example, we use the Comparable interface to define a natural ordering for the Student objects.
- By implementing the method, we specify how two Student objects should be compared by enabling sorting based on the student’s name.
- This allows us to use Arrays.sort() method directly on an array of Student objects to sort them in an order and here we do not need a separate comparator.