How to Sort an Array using Java

Sorting an array in Java involves arranging the elements of a list or array in a specific order, such as ascending or descending. This order can be based on numerical or lexicographical (alphabetical) criteria, which are commonly used for sorting operations.

In this section, we will explore methods to sort arrays in Java. We’ll cover sorting in both ascending and descending order, demonstrating how to achieve this using the sort() method and alternative approaches. Additionally, we’ll delve into sorting subarrays within the larger array.

Sorting of an Array in Java in Ascending Order

Ascending order refers to arranging elements from the lowest to the highest value. It is also known as natural order or numerical order. In Java, there are various ways to perform ascending order sorting, including using built-in sorting methods, implementing custom sorting algorithms, or leveraging sorting libraries. These approaches enable us to organize the elements of an array or list in ascending order efficiently.

  • Using the sort() Method
  • Without using the method
    • Using the Loop
    • Using the User-Defined Method

Sorting of an Array in Java using the sort() Method

In Java, the Arrays class from the java.util package offers a sort() method for sorting an array in ascending order. This method utilizes a Dual-Pivot Quicksort algorithm, which has a complexity of O(n log(n)). The sort() method is static, meaning it can be invoked directly using the class name. It takes an array of various data types such as int, float, double, long, char, and byte as its parameter and does not return anything.

Syntax:

public static void sort(int[] a)

Where a is an array to be short.

Sorting an Array using the sort() Method of the Arrays Class

In the following program, an integer array is defined. The sort() method from the Arrays class is then invoked, passing the array as the argument for sorting. To display the sorted array, a for loop is utilized.

SortArrayExample.java

import java.util.Arrays;   
public class SortArrayExample1  
{   
public static void main(String[] args)   
{   
//defining an array of integer type   
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};  
//invoking sort() method of the Arrays class  
Arrays.sort(array);   
System.out.println("Elements of array sorted in ascending order: ");  
//prints array using the for loop  
for (int i = 0; i < array.length; i++)   
{       
System.out.println(array[i]);   
}   
}  
}

Output:

In the given program, an alternative approach to print the array is by using the toString() method of the Arrays class. This method returns a string representation of the specified array, providing a convenient way to display the array’s contents.

System.out.printf(Arrays.toString(array));

Sorting of an Array in Java without using the Method

SortArrayExample1.java

public class SortArrayExample1 
{  
public static void main(String[] args)   
{  
//creating an instance of an array  
int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};  
System.out.println("Array elements after sorting:");  
//sorting logic  
for (int i = 0; i < arr.length; i++)   
{  
for (int j = i + 1; j < arr.length; j++)   
{  
int tmp = 0;  
if (arr[i] > arr[j])   
{  
tmp = arr[i];  
arr[i] = arr[j];  
arr[j] = tmp;  
}  
}  
//prints the sorted element of the array  
System.out.println(arr[i]);  
}  
}  
}

Output:

Sorting of an Array in Java using the User-Defined Method

SortArrayExample2.java

public class SortArrayExample2  
{  
public static void main(String[] args)   
{          
int i;  
//initializing an array  
int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27};  
System.out.print("Array elements before sorting: \n");  
for(i = 0; i < array.length; i++)  
System.out.println(array[i]);        
//invoking user defined method           
sortArray(array, array.length);  
System.out.print("Array elements after sorting: \n");      
//accessing elements of the sorted array     
for(i = 0; i <array.length; i++)  
{  
System.out.println(array[i]);  
}  
}  
//user defined method to sort an array in ascending order  
private static void sortArray(int array[], int n)   
{  
for (int i = 1; i < n; i++)  
{  
int j = i;  
int a = array[i];  
while ((j > 0) && (array[j-1] > a))   //returns true when both conditions are true  
{  
array[j] = array[j-1];  
j--;  
}  
array[j] = a;  
}  
}  
}

Output:

Sorting of an Array in Java in Descending Order

Descending order refers to arranging elements from the highest to the lowest value. It is the reverse of ascending order. In Java, there are various methods to perform descending order sorting, including using built-in sorting methods, implementing custom sorting algorithms, or leveraging sorting libraries.

  • Using the reverseorder() Method
  • Without using the method
    • Using for Loop
    • Using the User-Defined Method

Sorting of an Array in Java using the reverseorder() Method

In Java, the Collections class offers the reverseOrder() method for sorting an array in reverse-lexicographic order. This static method can be invoked directly using the class name and does not require any parameters. It returns a comparator that imposes the reverse of the natural ordering, resulting in descending-order sorting. By utilizing this method, we can efficiently arrange the elements of an array in reverse-lexicographic order.

By using the sort() method, the array sorts the elements in ascending order. Then, applying the reverseOrder() method on the sorted array reverses the natural ordering, resulting in the array being sorted in descending order.

Syntax:

public static <T> Comparator<T> reverseOrder()
Arrays.sort(a, Collections.reverseOrder());

SortArrayExample3.java

import java.util.Arrays;   
import java.util.Collections;   
public class SortArrayExample3   
{   
public static void main(String[] args)   
{   
Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205};   
// sorts array[] in descending order   
Arrays.sort(array, Collections.reverseOrder());   
System.out.println("Array elements in descending order: " +Arrays.toString(array));   
}   
}

Output:

Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9]

SortArrayExample4.java

import java.util.Arrays;   
import java.util.Collections;   
public class SortArrayExample4  
{   
public static void main(String[] args)   
{   
String [] strarray = {"Mango", "Apple", "Grapes", "Papaya", "Pineapple", "Banana", "Orange"};   
// sorts array[] in descending order   
Arrays.sort(strarray, Collections.reverseOrder());   
System.out.println("Array elements in descending order: " +Arrays.toString(strarray));   
}   
}

Output:

Array elements in descending order: [Pineapple, Papaya, Orange, Mango, Grapes, Banana, Apple]

Sorting of an Array in Java without using the Method in Descending Order

SortArrayExample5.java

public class SortArrayExample5  
{  
public static void main(String[] args)   
{  
int temp;  
//initializing an array  
int a[]={12,5,56,-2,32,2,-26,9,43,94,-78};  
for (int i = 0; i < a.length; i++)   
{  
for (int j = i + 1; j < a.length; j++)   
{  
if (a[i] < a[j])   
{  
temp = a[i];  
a[i] = a[j];  
a[j] = temp;  
}  
}  
}  
System.out.println("Array elements in descending order:");  
//accessing element of the array  
for (int i = 0; i <=a.length - 1; i++)   
{  
System.out.println(a[i]);  
}  
}  
}

Output:

Array elements in descending order:
94
56
43
32
12
9
5
2
-2
-26
-78

Sorting of an Array in Java using the User-Defined Method in Descending Order

SortArrayExample6.java

import java.util.Scanner;  
public class SortArrayExample6  
{  
public static void main(String[] args)   
{  
int n, temp;  
Scanner s = new Scanner(System.in);  
System.out.print("Enter the number of elements: ");  
n = s.nextInt();  
int a[] = new int[n];  
System.out.println("Enter the elements of the array: ");  
for (int i = 0; i < n; i++)   
{  
a[i] = s.nextInt();  
}  
for (int i = 0; i < n; i++)   
{  
for (int j = i + 1; j < n; j++)   
{  
if (a[i] < a[j])   
{  
temp = a[i];  
a[i] = a[j];  
a[j] = temp;  
}  
}  
}  
System.out.println("Array elements in descending order:");  
for (int i = 0; i < n - 1; i++)   
{  
System.out.println(a[i]);  
}  
System.out.print(a[n - 1]);  
}  
}

Output:

Enter the number of elements: 7
Enter the elements of the array: 
12
5
56
-2
32
2
-26
Array elements in descending order:
56
32
12
5
2
-2
-26

How to Sort Subarray

A subarray refers to an array derived from an existing array. For instance, given an array a[] with elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78], if we wish to sort the elements from index 34 to 18, we will be sorting the subarray [34, 2, 45, 3, 22, 18], while leaving the remaining elements unchanged. This allows for sorting a specific section of an array while preserving the order of the remaining elements.

To sort the subarray, the Arrays class in Java offers the static method sort(). This method enables sorting a specific range of elements within an array in ascending order. It supports sorting arrays of various types such as long, double, float, char, byte, and more. By utilizing the sort() method, we can conveniently arrange the elements of a subarray in the desired order.

Syntax:

public static void sort(int[] a, int fromIndex, int toIndex)

The method parses the following three parameters:

  • a: An array to be sorted.
  • fromIndex: The index of the first element of the subarray. It participates in the sorting.
  • toIndex: The index of the last element of the subarray. It does not participate in the sorting.

When using the sort() method from the Arrays class, it is important to note that if the fromIndex parameter is equal to the toIndex, it indicates an empty range to be sorted. Additionally, an IllegalArgumentException is thrown if the fromIndex value is greater than the toIndex. Similarly, an ArrayIndexOutOfBoundsException is thrown if the fromIndex is less than 0 or the toIndex exceeds the length of the array a. These exception cases need to be considered to ensure proper usage of the sort() method

SortSubarrayExample.java

import java.util.Arrays;   
public class SortSubarrayExample   
{   
public static void main(String[] args)   
{   
//defining an array  
int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78};  
// sorts subarray form index 2 to 7  
Arrays.sort(a, 2, 7);   
//prints array using the for loop  
for (int i = 0; i < a.length; i++)   
{       
System.out.println(a[i]);   
}   
}   
}

Output:

Sorted Subarray: 
12
90
2
3
22
34
45
18
5
78

In conclusion, sorting an array in Java can be accomplished using various methods, including the sort() method from the Arrays class. By utilizing this method, we can efficiently arrange the elements of an array in ascending order. Additionally, the Arrays class provides options for sorting subarrays, handling exceptions, and sorting arrays of different data types. Follow tutorials.freshersnow.com to learn more.