×

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

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java Class Syntax

A class is a fundamental building piece in object-oriented programming. It can be characterised as a template that outlines the information and actions connected to the creation of a class....

3 minutes read.

Ternary Operator in Java

In some cases, the if...else expression in Java can be replaced by a ternary operator. Visit the Java if...else statement first before learning about the ternary operator. Ternary operator in Java A...

3 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java Command not found

Java Command not found error is displayed if Java is not installed on the computer or if the command prompt cannot find Java.exe to run the program. Our Java software...

3 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

XOR Binary Operator in Java

One of the various Bitwise operators in Java is ava XOR. If two boolean operands are given, the XOR (also known as exclusive OR) returns true. When both of the...

4 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.