How to Sort an Array in Java

The sorting is a way to arrange elements of a list or array in a certain order. The order may be in ascending or descending order. The numerical and lexicographical (alphabetical) order is a widely used order.

In this section, we will learn how to sort array in Java in ascending and descending order using the sort() method and without using the sort() method. Along with this, we will also learn how to sort subarray in Java.

Sort Array in Ascending Order

The ascending order arranges the elements in the lowest to highest order. It is also known as natural order or numerical order. We can perform sorting in the following ways:

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

Using the sort() Method

In Java, Arrays is the class defined in the java.util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is O(n log(n)). It is a static method that parses an array as a parameter and does not return anything. We can invoke it directly using the class name. It accepts an array of type int, float, double, long, char, byte.

Syntax:

  1. public static void sort(int[] a)  

Where a is an array to be short.

Note: Like the Arrays class, the Collections class also provides the sort() method to sort the array. But there is a difference between them. The sort() method of the Arrays class works for primitive type while the sort() method of the Collections class works for objects Collections, such as LinkedList, ArrayList, etc.

Let’s sort an array using the sort() method of the Arrays class.

In the following program, we have defined an array of type integer. After that, we have invoked the sort() method of the Arrays class and parses the array to be sort. For printing the sorted array, we have used for loop.

SortArrayExample1.java

  1. import java.util.Arrays;   
  2. public class SortArrayExample1  
  3. {   
  4. public static void main(String[] args)   
  5. {   
  6. //defining an array of integer type   
  7. int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};  
  8. //invoking sort() method of the Arrays class  
  9. Arrays.sort(array);   
  10. System.out.println(“Elements of array sorted in ascending order: “);  
  11. //prints array using the for loop  
  12. for (int i = 0; i < array.length; i++)   
  13. {       
  14. System.out.println(array[i]);   
  15. }   
  16. }  
  17. }  

Output:

Array elements in ascending order: 
5 
12 
22 
23 
34 
67 
90 
109

In the above program, we can also use the toSting() method of the Arrays class to print the array, as shown in the following statement. It returns a string representation of the specified array.

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

Without Using the Method

Using the for Loop

In the following example, we have initialized an array of integer type and sort the array in ascending order.

SortArrayExample2.java

  1. public class SortArrayExample2  
  2. {  
  3. public static void main(String[] args)   
  4. {  
  5. //creating an instance of an array  
  6. int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65};  
  7. System.out.println(“Array elements after sorting:”);  
  8. //sorting logic  
  9. for (int i = 0; i < arr.length; i++)   
  10. {  
  11. for (int j = i + 1; j < arr.length; j++)   
  12. {  
  13. int tmp = 0;  
  14. if (arr[i] > arr[j])   
  15. {  
  16. tmp = arr[i];  
  17. arr[i] = arr[j];  
  18. arr[j] = tmp;  
  19. }  
  20. }  
  21. //prints the sorted element of the array  
  22. System.out.println(arr[i]);  
  23. }  
  24. }  
  25. }  

Output:

Array elements after sorting:
-65
-4
-1
1
3
6
20
34
34
55
78
90

Using the User Defined Method

In the following example, we have defined a method named sortArray() that contains the logic to sort an array in natural order.

SortArrayExample3.java

  1. public class SortArrayExample3  
  2. {  
  3. public static void main(String[] args)   
  4. {          
  5. int i;  
  6. //initializing an array  
  7. int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27};  
  8. System.out.print(“Array elements before sorting: \n”);  
  9. for(i = 0; i < array.length; i++)  
  10. System.out.println(array[i]);        
  11. //invoking user defined method           
  12. sortArray(array, array.length);  
  13. System.out.print(“Array elements after sorting: \n”);      
  14. //accessing elements of the sorted array     
  15. for(i = 0; i <array.length; i++)  
  16. {  
  17. System.out.println(array[i]);  
  18. }  
  19. }  
  20. //user defined method to sort an array in ascending order  
  21. private static void sortArray(int array[], int n)   
  22. {  
  23. for (int i = 1; i < n; i++)  
  24. {  
  25. int j = i;  
  26. int a = array[i];  
  27. while ((j > 0) && (array[j-1] > a))   //returns true when both conditions are true  
  28. {  
  29. array[j] = array[j-1];  
  30. j–;  
  31. }  
  32. array[j] = a;  
  33. }  
  34. }  
  35. }  

Output:

Array elements before sorting: 
12  
45  
1  
-1  
0  
4  
56  
23  
89  
-21  
56  
27  
Array elements after sorting: 
-21  
-1  
0  
1  
4  
12  
23  
27  
45  
56  
56  
89

Sort Array in Descending Order

The descending order arranges the elements in the highest to lowest order. We can perform sorting in the following ways:

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

Using the reverseOrder() Method

Java Collections class provides the reverseOrder() method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It returns a comparator that imposes the reverse of the natural ordering (ascending order).

It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.

Syntax:

  1. public static <T> Comparator<T> reverseOrder()  

Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder() method in the following way:

  1. Arrays.sort(a, Collections.reverseOrder());  

Let’s sorts an array in the descending order.

In the following program, a point to be noticed that we have defined an array as Integer. Because the reverseOrder() method does not work for the primitive data type.

SortArrayExample4.java

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

Output:

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

Let’s see another program that sorts array elements in alphabetical order.

SortArrayExample5.java

  1. import java.util.Arrays;   
  2. import java.util.Collections;   
  3. public class SortArrayExample5  
  4. {   
  5. public static void main(String[] args)   
  6. {   
  7. String [] strarray = {“Mango”, “Apple”, “Grapes”, “Papaya”, “Pineapple”, “Banana”, “Orange”};   
  8. // sorts array[] in descending order   
  9. Arrays.sort(strarray, Collections.reverseOrder());   
  10. System.out.println(“Array elements in descending order: ” +Arrays.toString(strarray));   
  11. }   
  12. }  

Output:

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

Without Using the Method

Using the for Loop

In the following example, we have initialized an integer array and perform sorting in descending order.

SortArrayExample6.java

  1. public class SortArrayExample6  
  2. {  
  3. public static void main(String[] args)   
  4. {  
  5. int temp;  
  6. //initializing an array  
  7. int a[]={12,5,56,-2,32,2,-26,9,43,94,-78};  
  8. for (int i = 0; i < a.length; i++)   
  9. {  
  10. for (int j = i + 1; j < a.length; j++)   
  11. {  
  12. if (a[i] < a[j])   
  13. {  
  14. temp = a[i];  
  15. a[i] = a[j];  
  16. a[j] = temp;  
  17. }  
  18. }  
  19. }  
  20. System.out.println(“Array elements in descending order:”);  
  21. //accessing element of the array  
  22. for (int i = 0; i <=a.length – 1; i++)   
  23. {  
  24. System.out.println(a[i]);  
  25. }  
  26. }  
  27. }  

Output:

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

Using the User Defined Method

SortArrayExample7.java

  1. import java.util.Scanner;  
  2. public class SortArrayExample7  
  3. {  
  4. public static void main(String[] args)   
  5. {  
  6. int n, temp;  
  7. Scanner s = new Scanner(System.in);  
  8. System.out.print(“Enter the number of elements: “);  
  9. n = s.nextInt();  
  10. int a[] = new int[n];  
  11. System.out.println(“Enter the elements of the array: “);  
  12. for (int i = 0; i < n; i++)   
  13. {  
  14. a[i] = s.nextInt();  
  15. }  
  16. for (int i = 0; i < n; i++)   
  17. {  
  18. for (int j = i + 1; j < n; j++)   
  19. {  
  20. if (a[i] < a[j])   
  21. {  
  22. temp = a[i];  
  23. a[i] = a[j];  
  24. a[j] = temp;  
  25. }  
  26. }  
  27. }  
  28. System.out.println(“Array elements in descending order:”);  
  29. for (int i = 0; i < n – 1; i++)   
  30. {  
  31. System.out.println(a[i]);  
  32. }  
  33. System.out.print(a[n – 1]);  
  34. }  
  35. }  

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

An array derived from the array is known as subarray. Suppose, a[] is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray [34, 2, 45, 3, 22, 18] and keep the other elements as it is.

To sort the subarray, the Arrays class provides the static method named sort(). It sorts the specified range of the array into ascending order. We can also sort the array of type long, double, float, char, byte, etc.

Syntax:

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

The method parses the following three parameters:

  • a: An array to be sort.
  • 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.

If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if fomIndex is greater than toIndex. It also throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length.

Let’s sort a subarray through a Java program.

SortSubarrayExample.java

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

Output:

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

Leave a Comment