Sorting is the process of arranging elements of an array in a certain order. The order can be ascending, descending, or lexicographical. Sorting is essential, as it makes searching for data more efficient and quick. Moreover, it is easy to carry out operations like accessing and storing the ordered data. Let’s discuss different ways to sort an array in Java.
How to Sort an Array in Ascending Order?
In ascending order, elements are arranged from lowest to highest order. It is widely known as natural order or numerical order. The sorting can be performed in three ways:
Using sort() Method
Using For loop
Using User-Defined Method
Using sort() Method
The Array class is defined in the java.util package and provides a sort() method to sort or arrange an array in ascending order. This method uses a Dual-Pivot Quicksort algorithm and has a time complexity of O(n log(n)). It is a static method and can be directly invoked using a class name. It accepts an array of types (int, float, double, long, and char) as an input parameter and doesn’t return anything.
Syntax: Arrays.sort();
Example:
import java.util.Arrays;
// Java program to sort integer array in ascending order using sort() method
public class SortArrayExample {
public static void main(String[] args){
// Define an integer type array
int[] arr = new int[] {120, 30, 11, 9, 200, 29};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Invoke sort method of Arrays class
Arrays.sort(arr);
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
The Original Array is:
120 30 11 9 200 29
The Sorted Array is:
9 11 29 30 120 200
In the above example, the sort() method is used to sort the given integer array in ascending order.
Using For loop
A nested for loop is used for sorting an array in ascending order.
Example:
// Java program to sort integer array in ascending order using for loop
public class SortArrayExample {
public static void main(String[] args){
// Define an integer type array
int[] arr = new int[] {120, 39, 101, -9, 20, 290, 0, -1};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Nested for loop sorting logic
int tmp;
// Starting the first for loop
for(int i = 0; i<arr.length; i++){
// Starting second for loop
for(int j = i+1; j<arr.length; j++){
// Comparing the elements
if(arr[j]<arr[i])
{
// Swapping and arrange them in ascending order
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
The Original Array is:
120 39 101 -9 20 290 0 -1
The Sorted Array is:
-9 -1 0 20 39 101 120 290
The above example shows the workings of nested loops to arrange a given array in ascending order.
Using the User-Defined Method
The other way to sort an array is to create a user-defined method. This method contains the sorting logic and can be reused multiple times in a program.
Example:
// Java program to sort integer array in ascending order using user-defined method
public class SortArrayExample {
public static void main(String[] args){
// Define an integer type array
int[] arr = new int[] {99, 39, 10, -9, 20, 2990, 0, -1, 13};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Invoking user-defined method
sortArrayInAsc(arr, arr.length);
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
//User-defined method to arrange elements of an array in the natural order
public static void sortArrayInAsc(int[] array, int n){
int tmp;
for(int i = 0; i<n; i++){
for(int j = i+1; j<n; j++){
if(array[j]<array[i])
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
}
}
Output:
The Original Array is:
99 39 10 -9 20 2990 0 -1 13
The Sorted Array is:
-9 -1 0 10 13 20 39 99 2990
In the above example, a user-defined method sortArrayInAsc() is created that arranges the elements of the array in natural order.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
How to Sort an Array in Descending Order?
In descending order, elements are arranged from highest to lowest order. The sorting can be performed in three ways:
Using reverseOrder() Method
Using For loop
Using the User-Defined Method
Using reverseOrder() Method
The reverseOrder() method sorts the given array in reverse-lexicographic order. It is also a static method and can be directly invoked using the class name. It doesn’t accept any input parameters and returns a comparator that imposes the reversal of natural order, i.e., descending order.
Syntax: public static Comparator reverseOrder()
Example:
import java.util.Arrays;
import java.util.Collections;
// Java program to sort integer array in descending order using reverseOrder() method
public class SortArrayExample {
public static void main(String[] args){
// Define an integer type array
Integer[] arr = {100, 3, -11, 9, 0, 120};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Invoke reverseOrder method of Java Collections class
Arrays.sort(arr, Collections.reverseOrder());
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
The Original Array is:
100 3 -11 9 0 120
The Sorted Array is:
120 100 9 3 0 -11
In the above example, the reverseOrder() method is used to sort the given integer array in descending order.
Using For loop
To sort the elements of an array in descending order, the nested for loop can be used.
Example:
import java.util.Arrays;
import java.util.Collections;
// Java program to sort integer array in descending order using reverseOrder() method
public class SortArrayExample {
public static void main(String[] args){
// Define an integer type array
Integer[] arr = {100, 3, -11, 9, 0, 120};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Invoke reverseOrder method of Java Collections class
Arrays.sort(arr, Collections.reverseOrder());
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
The Original Array is:
120 39 101 -9 20 290 0 -1
The Sorted Array is:
290 120 101 39 20 0 -1 -9
The above example shows the workings of nested loops to arrange a given array in descending order.
Using the User-Defined Method
Creating a user-defined method to sort an array in a specific order is also a widely known approach. This method contains the sorting logic and can be reused multiple times in a program.
Example:
// Java program to sort integer array in descending order using the user-defined method
public class SortArrayExample {
public static void main(String[] args){
// Define an integer type array
int[] arr = new int[] {909, 31, 10, -7, 20, 299, 0, -1, 13};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Invoking user-defined method
sortArrayInDsc(arr, arr.length);
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
//User-defined method to arrange elements of an array in descending order
public static void sortArrayInDsc(int[] array, int n){
int tmp;
for(int i = 0; i<n; i++){
for(int j = i+1; j<n; j++){ if(array[j]>array[i])
{
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}
}}
Output:
The Original Array is:
909 31 10 -7 20 299 0 -1 13
The Sorted Array is:
909 299 31 20 13 10 0 -1 -7
In the above example, a user-defined method sortArrayInDsc() is created that arranges the elements of the array in descending order.
How to Sort Subarray?
The contiguous part of an array is known as a subarray. To sort a subarray, the Arrays class provides a sort() method that can sort a specified range of an array in ascending or natural order. This static method can sort an array of type: long, double, float, char, etc. It accepts three parameters: the array, the index of the first element of the subarray, and the index of the last element of the subarray.
Syntax: Arrays.sort(arr, fromIndex, toIndex);
Example:
import java.util.Arrays;
// Java program to sort subarray in ascending order using the sort() method
public class SortSubarrayExample {
public static void main(String[] args){
// Define an integer type array
Integer[] arr = {100, 3, 11, 90, 0, 120, 17, 89};
// Printing the original array
System.out.println("The Original Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
// Invoke order method of Arrays class to sort subarray from starting index 2 to last index 5
Arrays.sort(arr, 2, 6);
// Printing the sorted array
System.out.println("nThe Sorted Array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Output:
The Original Array is:
100 3 11 90 0 120 17 89
The Sorted Array is:
100 3 0 11 90 120 17 89
In the above example, the sort() method is used to sort the subarray in ascending order, starting from index 2 to 5.
Conclusion
This concludes our discussion on the sorting of arrays in Java. We learned various methods to sort arrays in Java, including predefined functions, as well as traditional methods. We discussed how to sort an array in ascending and descending order and how to sort a subarray.
FAQs
Define Sorting in Java.
Sorting refers to the process of arranging data in ascending, descending, or alphabetical order. It can be achieved using the in-built sort method, loop, or user defined method.
What is the use of Sorting?
Sorting arranges the data in a certain order. It is useful as we can search for data more efficiently and swiftly. Also, it is easier to perform operations like accessing and storing an ordered data set.
Is it possible to Sort a List in Java?
Yes, it is possible. The list belongs to the Collections interface in Java and can be sorted using the predefined Collections interface’s sort() method.
What Sorting technique is used by the array sort in Java?
Arrays use dual-pivot Quicksort to sort primitive data types. It uses Merge Sort for sorting Objects.
What is a Comparator in Java? Why is it used?
Comparator is an interface that is defined within the java.util package. It is used to order the user-defined objects. It sorts the objects on the basis of their data members.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.