A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/arrays-sort-in-java/ below:

Arrays.sort() in Java - GeeksforGeeks

Arrays.sort() in Java

Last Updated : 08 Apr, 2025

Try it on GfG Practice

The Arrays.sort() method is used for sorting the elements in an Array. It has two main variations:

  1. Sorting the entire array (it may be an integer or character array)
  2. 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.

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:

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<Student> {
    
    // 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:

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<Student> {
    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:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4