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.
Sorting in Ascending Order
3.1.
Example
3.2.
Techniques
4.
Sorting Array in Descending Order
4.1.
Example
4.2.
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.
Frequently Asked Questions
9.1.
How much time does array sort take in Java?
9.2.
How to sort an array in Java?
9.3.
Do Arrays.sort() work on Strings?
9.4.
Can we use the Arrays.sort() method to sort arrays in descending order?
9.5.
Is it possible to sort a subarray using the Arrays.sort() method?
10.
Conclusion
Last Updated: Aug 31, 2024
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 an important topic from an interview perspective. It's the topic with which the programmers start their programming journey. Many sorting algorithms like the bubble sort, selection sort, merge sort, etc can be used to Sort Array in Java. There are certain in-built methods for sorting as well. This blog will look at one such method to Sort Array in Java which is present in the java.util package, the Arrays.sort() method, with various examples and code. Let's get started.

Sort Array in Java

Also see, Array Implementation of Queue 

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.

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]

Also Read - Selection Sort in C

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 to sort an array in Java?

You can use the Arrays.sort() method to sort arrays in Java.  

Do Arrays.sort() work on Strings?

Yes the method works for Strings as well.

Can we use the Arrays.sort() method to sort arrays in descending order?

Yes Arrays.sort() method can sort Array in descending order as well.

Is it possible to sort a subarray using the Arrays.sort() method?

Yes it is possible to sort a subarray using the Arrays.sort() method by passing in the start and end index to the sort() method.

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 -

 

Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass