Sorting Array in Java | Example Program

Sorting an array in Java means arranging elements of an array in a specific order i.e., either ascending or descending order.

Sorting, like searching, is the most common task in computer programming. It is the process of arranging a list of related elements in a specific order either in ascending or descending order.

For example, sorting a list of numbers from lowest to highest, sorting a list of items sold by an online store, or a list of customer names e-mail addresses.

Sorting an array in Java is very simple and easy because arrays class does all of the work for us. Java Arrays class provides a static sort() method to rearrange elements of an array in a specific order.

In this tutorial, we will learn how to sort an array in Java in ascending and descending order using the sort() method, without using the sort() method and Comparator interface. Along with this, we will also discuss how to sort a subarray in Java.

How to Sort Array in Ascending Order in Java?


Sorting an array in ascending order means arranging elements of an array from the lowest to highest. It is also known as numerical order or natural order.

There are the following ways by which we can sort elements of an array. They are as follows:

  • Using sort() method of Arrays class
  • Using for loop
  • Using Comparator interface

Let’s understand each way one by one.

Sorting array in Java

Sorting Array in Java using sort() method of Arrays class


In Java, Arrays class is defined in java.util package that provides a sort() utility method to sort array elements in ascending order.

It uses a dual-pivot quicksort algorithm for sorting. Its complexity is O(n log(n)).

The static sort() method of arrays class takes an array of type int, float, double, long, char, byte as a parameter and does not return anything.

Since it is a static method, we can call it directly using the class name. The general syntax for sort() method is as follows:

public static void sort(type[ ] array)

Note:

Like Arrays class, Collections class also provides sort() method to sort elements of an array. But there is a small difference between them.

The sort() method of the Arrays class works only with primitive type elements, whereas the sort() method of Collections class works with objects such as LinkedList, ArrayList, etc.

1. Let’s take a very simple program where we will sort elements of an array of type string using the sort() method of the Arrays class. We will call the sort() method of the Arrays class and passes the array to be sort. For displaying the sorted array, we will use for loop.

Program code:

package arraysProgram;
import java.util.Arrays;
public class SortingArray {
public static void main(String[] args) 
{
   String[ ] cities = {"Dhanbad", "Ranchi", "New York", "Tata Nagar", "Gaya", "Sydney", "Cape town", "Mumbai"};
   System.out.println("Original order: ");
   for(int i = 0; i < cities.length; i++)
   {
	System.out.println(i+ " " +cities[i]);
   }
   Arrays.sort(cities);
   System.out.println("New order after sorting: ");
   for(int j = 0; j <cities.length; j++)
   {
	System.out.println(j+ " " +cities[j]); 
   }
  }
}
Output:
      Original order: 
         0 Dhanbad
         1 Ranchi
         2 New York
         3 Tata Nagar
         4 Gaya
         5 Sydney
         6 Cape town
         7 Mumbai
     New order after sorting: 
        0 Cape town
        1 Dhanbad
        2 Gaya
        3 Mumbai
        4 New York
        5 Ranchi
        6 Sydney
        7 Tata Nagar

How to Sort an Array using for loop in Java?


Let’s take an example program where we will sort elements of an array of type integer. In this program, we will sort array elements using for loop.

Program code:

package arraysProgram;
public class SortingArray {
public static void main(String[] args) 
{
   int[ ] numbers = {25, 10, -10, 2, 30, 45, -1, 0};
   System.out.println("Original order: ");
   for(int i = 0; i < numbers.length; i++)
   {
      System.out.println(numbers[i]);
   }
   System.out.println("New order after sorting: ");
   for(int j = 0; j < numbers.length; j++)
   {
      for(int k = j + 1; k < numbers.length; k++) 
      { 
        int temp = 0; 
        if(numbers[j] > numbers[k])
        {
		temp = numbers[j];
		numbers[j] = numbers[k];
		numbers[k] = temp;
	}
      }
      System.out.println(numbers[j]);
    }
  }
}
Output:
       Original order: 
         25
         10
       -10
         2
         30
         45
        -1
         0
     New order after sorting: 
       -10
       -1
        0
        2
        10
        25
        30
        45

In this way, we can also sort elements of an array in natural or ascending order by using for loop.

Sorting Array in Ascending order using Comparator interface


Let’s take a simple example program where we will sort elements of an array of integer types using Comparator in Java. Here, we will use the Scanner class to accept array elements from the keyboard and sort them in ascending order. Look at the following source code to understand better.


Program code:

package arraysProgram;
import java.util.Arrays;
import java.util.Scanner;
public class SortingArrayUsingComp {
public static void main(String[] args) 
{
// Create an object of Scanner class to accept array elements from the keyboard.
   Scanner sc = new Scanner(System.in);	
   System.out.println("How many elements do you want to enter?");   
   int size = sc.nextInt();

// Create an array to store Integer type elements or objects.
   Integer arr[ ] = new Integer[size];
   System.out.println("Enter your number:"); 
   for(int i = 0; i < size; i++)
   {
	 arr[i] = sc.nextInt();
   }
// Create an object of Ascend class.
   Ascend as = new Ascend(); 
// Call sort() method of Arrays class to sort array elements in ascending order.
   Arrays.sort(arr, as); //  for sorting into ascending order.

// Display the sorted array elements.
   System.out.println("\nSorted in Ascending order: ");
   display(arr);
}  
static void display(Integer arr[ ])
{
  for(Integer element : arr)
  {
    System.out.println(element + "\t"); 
  }
 }
}
Output:
     How many elements do you want to enter?
       8
     Enter your number:
     -20
      20
      10
      05
    -05
    -100
      30
      40

   Sorted in Ascending order: 
    -100	
    -20	
    -5	
      5	
      10	
      20	
      30	
      40	

In this program, we have used the Scanner class to accept array elements from the keyboard. You can also use InputStreamReader class to accept elements of the array from the keyboard. For more detail, go to the Comparator interface tutorial.

How to Sort Array in Descending Order in Java?


Sorting an array in descending order means arranging elements from highest to lowest order. There are several ways to sort elements of an array in java in descending manner. They are as follows:

  • Using reverseOrder() Method of Collections class
  • Using for Loop
  • Using Comparator interface

Let’s understand each method one by one.

Sort Array in Descending order using reverseOrder() method


The reverseOrder() method was added by Java 8 to the Comparator interface. This static method helps in sorting a collection of elements in reverse order.

It returns a Comparator object that orders the collection’s elements in reverse order. The general syntax to declare reverseOrder() method is as follows:

public static Comparator reverseOrder()

Let’s take a simple program where we will sort string elements of an array in descending order (i.e. alphabetical order) by using reverseOrder() method.

Program code:

package arraysProgram;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Descend {
public static void main(String[] args) 
{
   String[ ] flowers = {"Rose", "Jasmin", "Lotus", "Sunflower", "Daisy", "Tulip", "Lavender"};
// Create and display a list containing flowers array elements.
   List list = Arrays.asList(flowers); // Creating a list.
   System.out.printf("Unsorted array elements: %s\n", list);

// Sorting elements of array in descending order using a comparator.
   Collections.sort(list, Collections.reverseOrder());
// Output List elements.
   System.out.printf("Sorted array elements: %s\n", list );
  }
}
Output:
         Unsorted array elements: [Rose, Jasmin, Lotus, Sunflower, Daisy, Tulip, Lavender]
         Sorted array elements: [Tulip, Sunflower, Rose, Lotus, Lavender, Jasmin, Daisy]

Let’s take another program where we will sort integer elements of an array in descending order using reverseOrder() method.

Program code:

package arraysProgram;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Descend {
public static void main(String[] args) 
{
   Integer[ ] nums = new Integer[]{2, 5, 8, -1, 0, 20, 6, 10};
// Create and display a list containing flowers array elements.
   List list = Arrays.asList(nums); // Creating a list.
   System.out.printf("Unsorted array elements: %s\n", list);

// Sorting elements of array in descending order using a comparator.
   Collections.sort(list, Collections.reverseOrder());
// Output List elements.
   System.out.printf("Sorted array elements in descending order: %s\n", list );
  }
}
Output:
      Unsorted array elements: [2, 5, 8, -1, 0, 20, 6, 10]
      Sorted array elements in descending order: [20, 10, 8, 6, 5, 2, 0, -1]

In this program, you will observe that we have defined an array of Integer type because the reverseOrder() method does not work for the primitive data type elements.

Sorting Array in Descending order using For loop


Let’s create a program where we will sort array elements of char type in alphabetical order without using any method. We will use for loop to sort array elements in descending order.

Program code:

package arraysProgram;
public class Descend {
public static void main(String[] args) 
{
  char temp;  
  char ch[] = {'s', 'c', 'i', 'e', 'n', 't', 'f', 'a', 'b', 'z', 'p'}; // Initializing char elements in the array.
  for (int i = 0; i < ch.length; i++)   
  {  
     for (int j = i + 1; j < ch.length; j++)   
     {  
	if (ch[i] < ch[j])   
	{  
	   temp = ch[i];  
	   ch[i] = ch[j];  
	   ch[j] = temp;  
	}  
     }  
  }  
  System.out.println("Sorting array elements in descending order:");  
// Accessing elements of the array one by one.
   for (int i = 0; i <= ch.length - 1; i++)   
   {  
     System.out.println(ch[i]);  
   }  
 }
}
Output:
         Sorting array elements in descending order:
          z
          t
          s
          p
          n
          i
          f
          e
          c
          b
          a

Program code:

package arraysProgram;
public class Descend {
public static void main(String[] args) 
{
   int temp;  
   int[] nums = {2, -2, -5, 0, 25, 10, 5, 8, 3}; // Initializing int elements in the array.
   for (int i = 0; i < nums.length; i++)   
   {  
      for (int j = i + 1; j < nums.length; j++)   
      {  
	  if (nums[i] < nums[j])   
	  {  
	     temp = nums[i];  
	     nums[i] = nums[j];  
	     nums[j] = temp;  
	  }  
      }  
   }  
   System.out.println("Sorting array elements in descending manner:");  
// Accessing elements of the array one by one.
   for (int i = 0; i <= nums.length - 1; i++)   
   {  
     System.out.println(nums[i]);  
   }  
 }
}
Output:
       Sorting array elements in descending order:
        25
        10
        8
        5
        3
        2
        0
      -2
      -5

Sort Array Elements in Descending order using Comparator


Let’s create a program to sort integer elements of an array in descending order using the Comparator interface.

Program code:

package arraysProgram;
import java.util.Comparator;
// Sorting elements into descending order.
public class Descend implements Comparator {
@Override 
public int compare(Integer i1, Integer i2)
{
  // For reverse comparison. 
     return i2.compareTo(i1);	
  }
}
package arraysProgram;
import java.util.Arrays;
import java.util.Scanner;
public class SortingArrayUsingComp {
public static void main(String[] args) 
{
  // Create an object of Scanner class to accept array elements from the keyboard.
     Scanner sc = new Scanner(System.in);	
     System.out.println("How many elements do you want to enter?");   
     int size = sc.nextInt();

  // Create an array to store Integer type elements or objects.
     Integer arr[ ] = new Integer[size];
     System.out.println("Enter your numbers:"); 
     for(int i = 0; i < size; i++)
     {
	 arr[i] = sc.nextInt();
     }
  // Create an object of Ascend class.
     Descend ds = new Descend(); 
  // Call sort() method of Arrays class to sort array elements in descending order.
     Arrays.sort(arr, ds); //  for sorting into descending order.

  // Display the sorted array elements.
     System.out.println("\nSorted in descending order: ");
     display(arr);
}  
static void display(Integer arr[])
{
    for(Integer element : arr)
    {
        System.out.println(element + "\t"); 
    }
  }
}
Output:
     How many elements do you want to enter?
       5
     Enter your numbers:
      -10
       5
       20
       1
       0
    Sorted in descending order: 
      20	
      5	
      1	
      0	
    -10	

How to Sort Subarray in Java?


An array obtained from another array is called subarray. For example, assume num[ ] is an array having elements [2, 9, 3, 5, 4, 10, 22, 18, 5, 7]. We want to sort subarray elements [3, 5, 4, 10, 22] of num[ ] and keep the other elements as it is.

To sort the subarray in java, Arrays class provides a static utility method named sort() that sorts elements in the specified range of the array into ascending order.

We can also sort elements of an array of type char, byte, long, double, float, etc. The general syntax to declare sort() method is as follows:

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

This method accepts the following three parameters:

  • array: It represents an array that has to be sort.
  • fromIndex: It represents the index of the first element of the subarray. It involves sorting.
  • toIndex: It represents the index of the last element of the subarray. It does not involve sorting.
  • If formIndex = toIndex, the range to be sorted is empty.
  • If fomIndex > toIndex then it throws IllegalArgumentException.
  • If fromIndex < 0 or toIndex > array.length, then it also throws ArrayIndexOutOfBoundsException.

Let’s take a simple example program to sort subarray elements of an array.

Program code:

package arraysProgram;
import java.util.Arrays;
public class SortingSubArray {
public static void main(String[] args) 
{
  // Creating an array of type int.  
     int[ ] num = {22, 9, 4, 45, 20, 3, 23, 7};  
  // Sorting subarray form index 2 to 6  
     Arrays.sort(num, 2, 6);   
     System.out.println("Sorted subarray elements from index 2 to 6: ");
  // Displaying array elements using for loop.  
     for (int i = 0; i < num.length; i++)   
     {       
	  System.out.println(num[i]);   
     }   
   }
}
Output:
       Sorted subarray elements from index 2 to 6: 
         22
         9
         3
         4
         20
         45
         23
         7

In this tutorial, we have elaborated enough points related to sorting array in Java with the help of all important example programs. Hope that you will have understood how to sort an array in ascending and descending order in Java. In the next, we will learn an array of objects in Java.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love