×

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used to sort.

There are various sorting techniques to sort an array using loops. However, Java provides two in-built methods to facilitate the sorting of array elements.

In this tutorial, we will learn how to sort an array using the following methods:

  • Using Arrays.sort() Method
  • Using reverseOrder() Method
  • Using Java for loop

Using Arrays.sort() Method

The Arrays.sort() method sorts the elements of primitive type and objects used to implement the comparable interface.

The Arrays.sort()method usesthe Dual Pivot Quicksort algorithm to sort primitive type elements and iterative mergesort to sort the objects.However, in the latest versions of Java, it uses Timsort.And its complexity is O(n log(n)).        

The main task of Arrays.sort() is to parse the array given in the argument. It can also be used to sort the sub-arrays. It is a static method and does not return anything. It can sort the arrays of type integer, float, double, char.

Syntax:

sort(array_name);          

The syntax to sort the selective array / subarray is:

sort(array_name, fromIndex, toIndex);

where,

fromIndex is the start of the subarray (inclusive), and toIndex is the end of the subarray (exclusive).

Let’s see some examples to sort arrays of different primitive types:

  • Sorting a Numeric array:

To sort an integer array in ascendingorder, we directly use the Arrays.sort().  It sorts the arrays in ascending order by default. We can also use the toString() method of the Arrays class to print the array.

Note: We can sort double, float, long arrays just like the integer array using sort() method.

NumericArraySort.java

 //importing necessary libraries
import java.util.Arrays;
public class NumericArraySort {
public static void main(String[] args)
{
//defining an integer array
int[] array_name = {45, 21, 66, 87, 32, 77, 1, 8, 33};
System.out.printf("Array before sorting: %s", Arrays.toString(array_name));
//sorting the array in ascending order
Arrays.sort(array_name);
System.out.printf("\n\nArray after sorting: %s\n", Arrays.toString(array_name));
}
} 

Output:

How to sort an array in Java

To sort an array in descending order the sort() method uses a second parameter Collections.reverseOrder(). Now we will see an example to sort an integer array in descending order.

Note: TheCollections.reverseOrder()is not applicable for primitive types. It works fine with arrays of objects.

NumericArrayRevSort.java

 //importing necessary libraries
import java.util.Arrays;
import java.util.Collections;
 public class NumericArrayRevSort
{
    public static void main(String[] args)
    {      
        Integer[] array_name = {45, 21, 66, 87, 32, 77, 1, 8, 33};
        //Printing the unsorted array
        System.out.printf("Array before sorting: %s",
                 Arrays.toString(array_name));
        //sorting array in descending order
        Arrays.sort(array_name, Collections.reverseOrder());
        //Printing sorted array
        System.out.printf("\n\nArray after sorting in descending order: %s\n",
               Arrays.toString(array_name));
    }
} 

Output:

How to sort an array in Java
  • Sorting a String array:

Like an integer array, we can sort string array using the sort() method of Array. When the string array is passed to the sort() method, it sorts the array in ascending alphabetical order. As discussed earlier, to sort the array in descending alphabetical order, we use the reverseOrder() method of Collections class as the second parameter of the sort() method.

Let us see an example to sort the string array:

StringArraySort.java

 //importing necessary libraries
import java.util.Arrays;
import java.util.Collections;
public class StringArraySort
{
    public static void main(String[] args)
    {
        String str_array[] = {"Guava", "Pineapple", "Apple", "Peach", "Grapes", "Banana"};
        System.out.printf("Array before sorting: \n%s\n\n", Arrays.toString(str_array));
        //sorting array in ascending order
        Arrays.sort(str_array);
        System.out.printf("String array sorted in ascending order: \n%s\n\n",                       
               Arrays.toString(str_array));
        //sorting array in descending order
        Arrays.sort(str_array, Collections.reverseOrder());
        System.out.printf("String array sorted in descending order : \n%s\n\n",
              Arrays.toString(str_array));
    }
} 

Output:

How to sort an array in Java
  • Sorting a character array

The sort() method also allows the sorting of a char array. There are two types of character array sort:

  1. Sorting complete array using sort(char[] array_name) method
  2. Sorting only the specified range of characters using sort(char[] array_name, int fromIndex_var, int toIndex_var) method where fromIndex_var is inclusive and toIndex_var is exclusive.

Let us see how to sort a character array in ascending order using the sort() method.

CharArraySort.java

 //importing necessary libraries
import java.util.Arrays;
public class CharArraySort {
  public static void main(String[] args) {
    //Creating a character array
    char[] charArray = new char[] { 'T', 'F', 'A', 'W', 'B', 'Q', 'M', 'C'};
    //Printing the array before sorting
    System.out.printf("\nChar Array before sorting : %s", Arrays.toString(charArray));
    //Sorting the Array
    Arrays.sort(charArray);
    //Printing the array after complete sort
    System.out.printf("\n\nChar Array after sorting : %s", Arrays.toString(charArray));
    // Defining another char array
    char[] charArray2 =
        new char[] { 'T', 'F', 'A', 'W', 'B', 'Q', 'M', 'C'};
    //Sorting a subarray / selective sorting
    Arrays.sort(charArray2, 2, 8);
    //Printing selectively sorted array
    System.out.printf("\n\nChar Array after selective sorting(2,8) : %s \n", Arrays.toString(charArray2));
  }
} 

Output:

How to sort an array in Java
  1. sort() method of Collections class

The sort() method of Collection class works for the objects Collections like the ArrayList, LinkedList, etc. When the collection elements are of Set type, we can use the TreeSet. To sort the elements of a List type, we use sort() and reverseOrder() methods.

Syntax:

Collections.sort(List list_name)

Consider the following example to understand how to sort the String objects of an ArrayList in ascending order:

CollectionsSort.java

 //importing necessary libraries
import java.util.*;
public class CollectionsSort {
    public static void main(String[] args)
    {
        // Create a list of strings
        ArrayList<String> array_name = new ArrayList<String>();
        array_name.add("Guava");
        array_name.add("Pineapple");
        array_name.add("Banana");
        array_name.add("Apple");
        array_name.add("Grapes");
        //Printing array before sorting
        System.out.println("Arrays before sorting:"+ array_name);
        //to sort in ascending order
        Collections.sort(array_name);
        //Printing the sorting array
        System.out.println("\nArrays after sorting:"+ array_name);
    }
} 

Output:

How to sort an array in Java

Let’s see an example to sort the String objects in descending order. For this we use reverseOrder() method.

CollectionsSortReverse.java

 import java.util.*;
public class CollectionsSortReverse{
    public static void main(String[] args)
    {
        // Create a list of strings
        ArrayList<String> array_name = new ArrayList<String>();
        array_name.add("Guava");
        array_name.add("Pineapple");
        array_name.add("Banana");
        array_name.add("Apple");
        array_name.add("Strawberry");
        array_name.add("Kiwi");
        //Printing array before sorting
        System.out.println("\nArrays before sorting:"+ array_name);
        //Sorting array in descending order
        Collections.sort(array_name, Collections.reverseOrder());
        System.out.println("\nDescending array after sorting:"+ array_name);
    }
} 

Output:

How to sort an array in Java

Using the for loop

We can sort an array manually using for loops. The loops traverse the array and compare the adjacent elements and then put them in the proper order.

Here we use two for loops, one to traverse the array from the start and another for loop, which is nested inside the outer loop to traverse the next element.

There are various types of sorting techniques to sort the arrays using for loops.

Click here to learn about different sorting algorithms with examples.

Here we will see the example of the Bubble Sort algorithm, which is the simplest sorting algorithm. In this algorithm, each element of an array is compared to the adjacent element.

ForLoopSort.java

 public class ForLoopSort {
public static void main(String[] args) { 
    int[] a = {43, 23, 11, 67, 33, 10, 5, 22, 70};
    int n = a.length;
    int i,j;
    //printing array before sorting
    System.out.println("\nArray before sorting:");
    for(i = 0; i < n; i++){
        System.out.print(a[i]+ " ");
    }
    for(i=0; i<n; i++) 
    { 
        for (j=0 ;j<n; j++) 
        { 
            if(a[i]<a[j]) 
            { 
                int temp = a[i]; 
                a[i]=a[j]; 
                a[j] = temp;  
            } 
        } 
    } 
    System.out.println("\n\nArray after bubble sort:"); 
    for(i=0; i<n; i++) 
    { 
        System.out.print(a[i]+ " "); 
    } 
    System.out.println();
} 
}  

Output:

How to sort an array in Java

We can also write a user-defined method to sort an array. In the following example, we are using the method named sort_array().

ArraySort.java

 public class ArraySort { 
    public static void main(String[] args) { 
    int[] a = {43, 23, 11, -4, 67, 33, 10, -2, 5, 22, 70};
    int n = a.length;
    int i,j;
    //Printing array before sorting
    System.out.println("\nArray before sorting:");
    for(i = 0; i < n; i++){
        System.out.print(a[i]+ " ");
    }
    sort_array(a, n); //passing the array and the length of array
    System.out.println("\n\nArray after bubble sort:"); 
    for(i=0; i<n; i++) 
    { 
        System.out.print(a[i]+ " "); 
    } 
    System.out.println();
} 
    public static void sort_array(int arr[], int len){
        for(int i=0; i<len; i++) 
        { 
                for (int j=0 ;j<len; j++) 
                { 
                    if(arr[i]<arr[j]) 
                    { 
                        int temp = arr[i]; 
                        arr[i]=arr[j]; 
                        arr[j] = temp;  
                    } 
                } 
        } 
    }
}  

Output:

How to sort an array in Java

In this way, we have learned how to sort an array in Java using the build-in methods andusing the Java for loop.


Related Topics

Topological Sort In Java

Topological Sort in Java Topological sort is mainly used in the linear ordering of vertices in a Directed Acyclic Graph (DAG). Topological sort in Java illustrates how to do the linear ordering of...

1 minute read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Java Math atan2() Method

The atan2() method of Math class returns an angle theta from the conversion of rectangular coordinates to polar coordinates. Syntax: public static double atan2(double y, double x) Parameters: The parameter ‘y’ represents the ordinate...

3 minutes read.

Java String hashCode() method

Java String hashCode() method returns hash code for current String. hash code for string object is computed as s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] Using int...

2 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Dictionary in Java

Dictionary in Java The Dictionary class represents a key-value relation which maps keys to values. In Dictionary class, every key and every value is an object. It is an abstract class associated with...

2 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.