Table of contents
1.
Introduction
2.
How to Sort an Array in Java
2.1.
Syntax: sort() Method
2.2.
Syntax: Overloaded sort() Method
2.3.
Parameters
2.4.
Return Type
3.
Why Sorting Arrays Is Important in Java Programming?
4.
Sorting in Ascending Order
4.1.
Example
4.2.
Techniques
4.3.
Sorting Array in Descending Order
4.4.
Example
4.5.
Techniques
5.
Example 1: Sort Array in Java
5.1.
Java
6.
Example 2: Sort Array in Java
6.1.
Java
7.
Example 3: Sort Array in Java
7.1.
Java
8.
Example 4: Sort Array in Java
8.1.
Java
9.
Sort Array Using Loops in Java (Manual Sorting)
9.1.
1. Bubble Sort Using Loops
9.2.
2. Selection Sort Using Loops
10.
Sort Array Using User-Defined Method in Java
10.1.
Example: Sorting Array Using Bubble Sort in a Method
11.
Implementing Custom Sorting Using Comparator in Java
11.1.
Example: Sorting a List of Employees by Name and Age
12.
When to Use Which Sorting Method
13.
Real-World Use Cases of Array Sorting
14.
Frequently Asked Questions
14.1.
How much time does array sort take in Java?
14.2.
How do you sort an array in descending order in Java?
14.3.
Can you use sort() on an array?
15.
Conclusion
Last Updated: Jul 6, 2025
Easy

Sort Array in Java

Author Manvi Chaddha
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sorting is a fundamental operation in programming, and Java provides simple ways to sort arrays efficiently. To sort array in Java, developers commonly use Arrays.sort() in Java, which is part of the java.util package. Whether you're working with integers, strings, or custom objects, the Java sort array functionality ensures optimal performance and clean code for various sorting needs.

Sort Array in Java

How to Sort an Array in Java

In Java as with any other programming language, you can sort Array with any Sorting algorithm like Bubble sort, Selection Sort etc. However, you can also use the in-built Arrays.sort() method to sort Array.  
Inside the java.util package, there is a class called Array. Inside the Array class, several methods are used to manipulate arrays, such as sorting and searching and contain a static factory that allows arrays to be viewed as lists. 
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending,  built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values. This method can be used to Sort Array of integers, strings, floating point numbers and so on.The sorting algorithm is a Dual-Pivot Quicksort by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm offers O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance, and is typically faster than traditional (one-pivot) Quicksort implementations.

Syntax: sort() Method

The syntax of the method to sort Array in Java is:

Arrays.sort()

Syntax: Overloaded sort() Method

You can use the overloaded sort() method to Sort Array in Java, the syntax is given below:

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

The difference between the two methods is in the overloaded sort method to Sort Array in Java, you pass two additional parameters, the start and end index of the array. Note that it's not compulsory to include the start and end index; however, if you want only a subsection of the array to be sorted, you can use the overloaded syntax.

Parameters

The three parameters passed in the sort() method used to Sort Array in Java are described as follows:-

  • int[] arr -> This represents the array that is to be sorted
  • from_index -> The index of the first element from where the sorting takes place.
  • end_index -> The index of the last element till where the sorting takes place. 

Return Type

The method does not return any value. 
Let’s check the implementation of the sort() method by taking various examples.

Why Sorting Arrays Is Important in Java Programming?

Sorting plays a critical role in both real-world and programming contexts. Below are three key reasons that highlight the importance of sorting in Java, along with examples and use cases to help learners understand why sort arrays in Java is a must-know concept.

Type 1: Improves Data Accessibility and Search Performance
Sorting arrays improves search efficiency, especially with techniques like binary search, which requires a sorted array to work correctly. For instance, finding a name in a sorted list of students is faster than scanning through an unsorted list. Sorted arrays are also foundational in real-time systems and many data structures, such as trees and heaps, which rely on order for quick access.

 

Type 2: Essential for Efficient Algorithm Implementation
Sorting is often a preprocessing step for many efficient algorithms, such as merge sort, quick sort, and binary search. It reduces the overall time complexity when processing large datasets. For example, in a stock market application, sorting stock prices before filtering or analyzing trends ensures faster computation and scalability in performance-sensitive systems.

 

Type 3: Real-World Application Relevance
The use of array sorting in real-life applications is everywhere—e-commerce sites sort products by price, ratings, or popularity; schools sort student records by grades; companies organize employee data by ID or salary. Java developers rely on sorting to enhance user experience, streamline financial operations, and enable fast database filtering and analytics.

Sorting in Ascending Order

Sorting an array in ascending order arranges the elements from the smallest to the largest. This is a common task in data processing and is often used to prepare data for further analysis or operations. Sorting in ascending order ensures that the smallest value appears first, followed by larger values in increasing order.

Example

Given an array: [5, 2, 9, 1, 5, 6]

After sorting in ascending order: [1, 2, 5, 5, 6, 9]

Techniques

  • Bubble Sort: Compares adjacent elements and swaps them if they are in the wrong order. Repeats this process until the array is sorted.
  • Insertion Sort: Builds the sorted array one item at a time by inserting each element into its correct position.
  • Merge Sort: Divides the array into smaller sub-arrays, sorts them, and then merges them back together.
  • Quick Sort: Selects a pivot element, partitions the array into elements less than and greater than the pivot, and recursively sorts the partitions.

Sorting Array in Descending Order

Sorting an array in descending order arranges the elements from the largest to the smallest. This is useful for scenarios where you need to prioritize or view the largest values first. Descending order ensures that the largest value appears first, followed by smaller values in decreasing order.

Example

Given an array: [5, 2, 9, 1, 5, 6]

After sorting in descending order: [9, 6, 5, 5, 2, 1]

Techniques

  • Bubble Sort: Similar to ascending order, but swaps adjacent elements if they are in the wrong order for descending sorting.
  • Insertion Sort: Inserts each element into its correct position in a sorted portion of the array but in descending order.
  • Merge Sort: Divides the array, sorts sub-arrays in descending order, and then merges them.
  • Quick Sort: Partitions around a pivot, ensuring larger elements come before smaller ones, and recursively sorts the partitions.

Example 1: Sort Array in Java

Let’s look at a simple example that will sort the array of integers in ascending order.

  • Java

Java

// Example showing how to sort array in Java
import java.util.Arrays;
class Solution {
   public static void main(String[] args) {
       int[] arr = {45, 21, 9, 101, 13, 7};
       Arrays.sort(arr);
       // toString() method is used for formatting
       System.out.println(Arrays.toString(arr));
   }
}
You can also try this code with Online Java Compiler
Run Code

The output of the above program is 

[7, 9, 13, 21, 45, 101]

Example 2: Sort Array in Java

In this example we will only sort  the subarray using the overloaded sort syntax. Note that in this example only the subarray from the start till the end index will be sorted. The remaining subarray will be as it is.

  • Java

Java

// Example showing how to sort Array in Java
import java.util.Arrays;
class Solution {
   public static void main(String[] args) {
       int[] arr = {45, 21, 9, 5, 13, 7};
       // Sort the subarray from index 1(inclusive) till index 4(exclusive)
       // That is the elements 21, 9, 5
       Arrays.sort(arr, 1, 4);
       // toString() method is used for formatting
       System.out.println(Arrays.toString(arr));
   }
}
You can also try this code with Online Java Compiler
Run Code

The output of the above program is 

[45, 5, 9, 21, 13, 7]  

Example 3: Sort Array in Java

Till now we have only checked ascending order of arrangement of elements, but sorting in descending order is also possible by a little tweak. You can use the reverseOrder() method inside the Collections package to do so as shown below

  • Java

Java

// Example showing how to Sort array in Java
import java.util.Arrays;
import java.util.Collections;
class Solution {
   public static void main(String[] args) {
       // We have used Integer[] instead of int[]
       // as Collections.reverseOrder() does not work
       // for primitive types
       Integer[] arr = {45, 21, 9, 5, 13, 7};
       // Sorts arr[] in descending order using
       // reverseOrder() method of Collections class
       // in Array.sort() as an argument to it
       Arrays.sort(arr, Collections.reverseOrder());
       // toString() method is used for formatting
       System.out.println(Arrays.toString(arr));
   }
}
You can also try this code with Online Java Compiler
Run Code

The output of the above program is: 

[45, 21, 13, 9, 7, 5]

Example 4: Sort Array in Java

Let’s now sort an Array of Strings in the below example

  • Java

Java

// Example showing how to sort array in Java
import java.util.Arrays;
import java.util.Collections;
class Solution {
   public static void main(String[] args) {
    
       String[] arr = {"Coding", "Ninjas", "is", "the", "best"};
       // Sorts arr[] in descending order using
       // reverseOrder() method of Collections class
       // in Array.sort() as an argument to it
       Arrays.sort(arr, Collections.reverseOrder());
       // toString() method is used for formatting
       System.out.println(Arrays.toString(arr));
   }
}
You can also try this code with Online Java Compiler
Run Code

The output of the above program is: 

[the, is, best, Ninjas, Coding]

Sort Array Using Loops in Java (Manual Sorting)

Manual sorting helps beginners understand how sorting works internally. It builds a strong base for learning advanced data structures and algorithms.

1. Bubble Sort Using Loops

Bubble Sort compares each pair of adjacent elements and swaps them if they are in the wrong order. This process repeats until the array is sorted.

Example

public class BubbleSortExample {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 3, 1};
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // swap
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        // Print sorted array
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

Explanation:

  • Two loops are used: one for passes and the other for comparing adjacent elements.
     
  • If an element is greater than the next one, they are swapped.
     
  • After all passes, the array becomes sorted.

2. Selection Sort Using Loops

Selection Sort works by finding the smallest element in the array and swapping it with the first unsorted element.

Example:

public class SelectionSortExample {
    public static void main(String[] args) {
        int[] arr = {7, 4, 1, 9, 2};
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }

            // Swap smallest with current element
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }

        // Print sorted array
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

Explanation:

  • For each position, find the smallest number in the remaining array.
     
  • Swap that smallest value with the current position.
     
  • Repeat until the array is sorted.

Sort Array Using User-Defined Method in Java

Using user-defined methods in Java makes your code clean, reusable, and easy to manage. It allows you to sort different arrays using the same function.

Example: Sorting Array Using Bubble Sort in a Method

Code

public class SortWithMethod {
    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    // swap
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] numbers = {6, 3, 9, 1, 5};

        // Call the sorting method
        bubbleSort(numbers);

        // Display sorted array
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}
You can also try this code with Online Java Compiler
Run Code

Explanation:

The bubbleSort method handles sorting logic.

  • In the main method, we call this the user-defined method and pass the array.
     
  • After sorting, we print the array in the sorted order.

Implementing Custom Sorting Using Comparator in Java

In Java, the Comparator interface is used to define custom sorting logic, especially when the default sorting order (as defined by Comparable) doesn’t meet your needs. It allows sorting objects based on different attributes without modifying the original class.

Example: Sorting a List of Employees by Name and Age

import java.util.*;

class Employee {
    String name;
    int age;

    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return name + " - " + age;
    }
}

class SortByName implements Comparator<Employee> {
    public int compare(Employee a, Employee b) {
        return a.name.compareTo(b.name);
    }
}

class SortByAge implements Comparator<Employee> {
    public int compare(Employee a, Employee b) {
        return a.age - b.age;
    }
}

public class CustomSortExample {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>();
        list.add(new Employee("John", 28));
        list.add(new Employee("Alice", 24));
        list.add(new Employee("Bob", 30));

        Collections.sort(list, new SortByName());
        System.out.println("Sorted by Name: " + list);

        Collections.sort(list, new SortByAge());
        System.out.println("Sorted by Age: " + list);
    }
}
You can also try this code with Online Java Compiler
Run Code


Output:

Sorted by Name: [Alice - 24, Bob - 30, John - 28]
Sorted by Age: [Alice - 24, John - 28, Bob - 30]

 

Using Comparator provides flexibility to sort objects based on multiple fields without changing the original class. It is ideal for custom sorting scenarios in real-world Java applications.

When to Use Which Sorting Method

Type 1: Manual Sort vs Built-in Sort (Use Cases & Benefits)
Manual sorting in Java—such as bubble sort or selection sort—is useful when you're learning how sorting algorithms work or when you need custom control over sorting steps. These approaches are ideal for interview preparation and understanding core logic.
On the other hand, in real-world or production-level code, use built-in methods like Arrays.sort() or Collections.sort(). These methods are optimized for performance, handle edge cases internally, and are better for sorting large datasets. They also improve code readability and reduce the chance of errors, making them the preferred choice in software development.

 

Type 2: Performance and Readability Considerations
Built-in sorting methods like Arrays.sort() use efficient algorithms such as Timsort or dual-pivot Quicksort, offering average time complexities of O(n log n). In contrast, manual methods like bubble sort or insertion sort often have O(n²) complexity, making them inefficient for large datasets.
In terms of readability, built-in methods are cleaner and easier to maintain, especially when working in teams or contributing to shared codebases. That said, manual sorting is valuable for learning algorithm fundamentals and improving your problem-solving skills during interviews.

Use built-in methods for performance and clarity; use manual sorting in Java for educational purposes.

Real-World Use Cases of Array Sorting

Type 1: E-commerce – Sorting Product Listings
In e-commerce platforms, array sorting is crucial for enhancing user experience. Products are often sorted by price (low to high), ratings, or popularity to help users find relevant items quickly. Behind the scenes, developers use sorting logic to arrange product arrays based on selected filters. This improves search efficiency and increases conversion rates.

A perfect example of real-world applications of array sorting in retail platforms.

 

Type 2: Data Analytics – Preparing Datasets
In data analysis, sorting is often a preprocessing step used to organize datasets. For example, before generating graphs or performing trend analysis, you might sort sales data by date or log entries by timestamp. This ensures the data is structured properly for accurate interpretation and visualization.

A common case of Java array sorting examples in analytics workflows.
 

 Type 3: Competitive Exams or Leaderboards
Sorting plays a key role in ranking systems, such as arranging student scores, coding contest results, or player statistics. In real-time apps or games, scores are constantly updated and sorted dynamically to reflect leaderboard changes. Developers use efficient sorting to handle this without performance lags.

A great illustration of use cases of sorting in Java for scoring and performance tracking.

Frequently Asked Questions

How much time does array sort take in Java?

In Java, array sorting typically uses the dual-pivot Quicksort algorithm for primitives, which has an average-case time complexity of O(nlog⁡n)O(nlogn) and a worst-case of O(n2)O(n2). For objects, Timsort is used, which also averages O(nlog⁡n)O(nlogn).

How do you sort an array in descending order in Java?

Use Arrays.sort(array, Collections.reverseOrder()) for object arrays like Integer[]. It sorts the array in descending order using a reverse comparator.

Can you use sort() on an array?

Yes, you can use Arrays.sort() in Java to sort arrays in ascending order. It works for both primitive and object arrays efficiently.

Conclusion

In this article, we learned about sorting arrays in Java. We discussed the syntax, algorithms, and different code examples to show how to efficiently sort elements in ascending or descending order. Array sorting techniques are very useful because, with this, developers can optimize data organization and could improve the performance of their Java applications.

Recommended problems -

Live masterclass