paint-brush
How to Sort an Array in Java - A Complete Tutorialby@sharmapk752
196 reads

How to Sort an Array in Java - A Complete Tutorial

by Pankaj SharmaAugust 27th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Sorting is like arranging a deck of cards in a certain order, from the smallest to the largest or vice versa.
featured image - How to Sort an Array in Java - A Complete Tutorial
Pankaj Sharma HackerNoon profile picture

Sorting an array is a fundamental task in many programming languages. Java languages provide a diverse range of methods to achieve this. In this article, we will cover a variety of methods to sort arrays in Java, including the built-in methods and some custom implementations. By the end of this guide, you will have a comprehensive understanding of how to sort arrays efficiently in Java.


What is sorting?

Sorting is like arranging a deck of cards in a certain order, from the smallest to the largest or vice versa. In programming, it's a way to arrange elements in a list or array in a certain order, which may be ascending or descending. A sorting algorithm rearranges elements according to a comparison operator on the elements. The comparison operator decides the new order of elements in the respective data structure.


Sort Array in Ascending Order


Ascending order means arranging the elements in the lowest to highest order. It is also known as natural order or numerical order.


In Java, we can sort the array 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, Array is the class defined in the java.util. package provides a sort() method to sort an array in ascending order. This method uses a Dual-Pivot Quicksort Algorithm, whose complexity is O(n log(n)). It is a static method that parses an array as a parameter and does not return anything. This method accepts an array of types: int, float, double, long, char, and byte.


Syntax


public static void sort(int[]array)


The following program demonstrates the sort() method of the Arrays class.


Program


import java.util.Arrays;

class Main{
    public static void main(String args[]){
        int [] array  = new int []{33,2,34,534,1,93} ;
        Arrays.sort(array)  ;

        for (int i : array) {
             System.out.print(i+" ");
        }
    }
}


Output


1 2 33 34 93 534


Without Using the Method


Using the for Loop


The following program demonstrates the for loop initialized by an array of integer types and sorting the array in ascending order.


Program


public class SortingExample {  
public static void main(String[] args) {  
  int[] arr = new int[] {435,93,34,53,12,334,53,34,23,34};  
  System.out.println("Array elements after sorting: ");  
 
  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;  
    }  
  }  
      System.out.print(arr[i]+" ");  
    }  
   }  
}  


Output

Array elements after sorting: 12 23 34 34 34 53 53 93 334 435


Using the User-Defined Method


We can also sort the array using the user-defined method. We have defined a method named sortArray() that contains the logic to sort an array in natural order.


The following program demonstrates the user-defined method.


Program


public class Main {
    public static void main(String[] args) {
        int i;
        int array[] = { 34,55,99,23,5,34, 21,1};
        System.out.print("Array elements before sorting: \n");

        for (i = 0; i < array.length; i++)
            System.out.print(array[i]+" ");
        sortArray(array, array.length);
            System.out.println() ;
        System.out.print("Array elements after sorting: \n");

        for (i = 0; i < array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }

    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)){
                array[j] = array[j - 1];
                j--;
            }
            array[j] = a;
        }
    }
}


Output


Array elements before sorting: 34 55 99 23 5 34 21 1 Array elements after sorting: 1 5 21 23 34 34 55 99


Sort Array in Descending Order


Descending order arranges the elements from the highest to the lowest order. We can perform descending order 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


The reversOrder() method is defined in the collection framework classes. It is a convenient way to sort arrays in descending order. It returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the ‘Comparable’ interface.

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


Syntax


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


Program


import java.util.Arrays;  
import java.util.Collections;


class Main{  
public static void main(String[] args)   {  
    Integer [] array = {3,4,1,5,9,3,4};  
    Arrays.sort(array, Collections.reverseOrder());  
    System.out.println("Array elements in descending order: " +Arrays.toString(array));  
  }  
} 


Output


Array elements in descending order: [9, 5, 4, 4, 3, 3, 1]


Program: The following program sorts array elements in alphabetical order.


import java.util.Arrays;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        String[] strarray = { "Harry", "Potter", "Voldemort", "Computer", "Singhaniya", "Watermelon" };

        Arrays.sort(strarray, Collections.reverseOrder());
        System.out.println("Array elements in descending order: " + Arrays.toString(strarray));
    }
}


Output


Array elements in descending order: [Watermelon, Voldemort, Singhaniya, Potter, Harry, Computer]


Without Using the Method


The following program sorts the array using the loop. We have initialized an integer array and performed sorting in descending order.

Program


public class Main {
    public static void main(String[] args) {
        int temp;
        int a[] = { 12,5,9, 1, 4, 2,5, 9, 34, 53 };
        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.print(a[i]+" ");
        }
    }
}


Output


Array elements in descending order: 53 34 12 9 9 5 5 4 2 1


Using the User-Defined Method


Program


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int temp;
       
        int a[] = {33,4,5,3,31,2,3} ;
        int len = a.length ;

        System.out.println("Array Elements Before Sorting") ;
        for (int i : a) {
            System.out.print(i+" ");
        }

        System.out.println();
       
        for (int i = 0; i < a.length-1; 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:");
        for (int i = 0; i < len; i++) {
            System.out.print(a[i]+" ");
        }
        System.out.print(a[len-1]);
    }
}


Output


Array Elements Before Sorting 33 4 5 3 31 2 3 Array elements in descending order: 33 31 5 4 3 3 2 2


How to Sort Subarray


An array derived from the array is known as a subarray. Suppose we have an array[] with the following elements in the array [12,90,43, 53, 23, 34, 1, 33, 5], and we want to sort array elements from 43 to 33 and keep the other elements as it is.


To sort a subarray, The Arrays class provides the static method name sort(). This method sorts the specified range of the array into ascending order. This method can sort any array type: long, double, float, char, byte, etc.


Syntax


public static void sort(int[] arr, int startIndex, int lastIndex)


This method takes three parameters.


● arr[]. An array to be sorted. ● startIndex: The index of the first element of the subarray. It participates in the sorting. ● lastIndex: The index of the last element of the subarray. It does not participate in the sorting.


If the startIndex is equal to the lastIndex. The range to be sorted is empty. It throws IllegalArgumentException. If the startIndex is greater than the lastIndex. Then, it will throw ArrayIndexOutOfBoundException.


The following program demonstrates sort() method in Java


Program


import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = { 33, 23, 1, 53, 2, 4,9, 1};
        Arrays.sort(a, 2, 7);
        System.out.print("Sorted Array = ") ;
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]+" ");
        }
    }

}


Output


Sorted Array = 33 23 1 2 4 9 53 1


Conclusion


In this article, we learned about sorting arrays in Java. It is a fundamental skill that every Java developer should master. The ‘Arrays’ class provides a powerful and easy-to-use method for sorting entire arrays or specific subarrays. Understanding How to utilize methods effectively can significantly enhance the performance and readability of your code.


Frequently Asked Questions


  1. What methods are available for sorting arrays in Java?


Java language provides the ‘Arrays.sort()’ method for sorting arrays. It can sort arrays of primitives and objects and supports sorting subarrays.


  1. Can I sort an array of custom objects?


Yes, we can sort an array of custom objects by implementing a ‘Comparable’ interface in your class or by providing a ‘Comparator’ to the ‘Arrays.sort()’ method.


  1. Can I sort arrays with null elements?


In Java, if you sort an array with a null element, it will throw a ‘NullPointerException’. If the array is of a reference type, ensure that null elements are handled or removed.


  1. Can I sort an array of boolean values?


We cannot directly sort the array boolean values in Java using the Arrays.sort() method. However, we can convert the boolean value to integers (0 and 1), sort the integer array, and then convert it back to boolean values.