How to sort an array in Java


JavaViews 4151

Sorting is an important concept in arrays. In this tutorial, we will see various methods on how to sort an array in Java with examples. Sorting is a technique to arrange the elements in either ascending or descending order based on numbers or alphabets. Ascending order denotes sorting elements starting from low value until high value. Descending order sorts the elements starting from high value until low value.

How to sort an array in Java

Different ways on how to sort an array in Java

There are different approacheson how to sort an array in Java. We can use either of the below methods:

  • Arrays.sort() method
  • Without using the sort method
    •  for loop
    • user-defined method
    • comparator

Sorting arrays in Java

 

Sort in Ascending order: Using the sort method

The Arrays class contains a static sort() method that automatically sorts the elements in ascending order. It sorts the elements based on the dual-pivot Quicksort algorithm. The complexity of this method is O(n log(n)). We can sort elements of type int, float, double, long, char, and byte. The sort method accepts the array variable as a parameter.

public static void sort(int[] arrayName)

Now we will see an example of how to sort an array in Java using the sort() method. We can directly print the array elements by using the Arrays.toString() method and pass the array variable as a parameter.

import java.util.Arrays;

public class SortArray {

  public static void main(String[] args) {
    int[] arrNum = {45,12,78,34,67,10,55,44};
    
    System.out.println("Arrays in original order: " + Arrays.toString(arrNum));
    
    Arrays.sort(arrNum);
    
    System.out.println("Sorted arrays in ascending order: " + Arrays.toString(arrNum));

  }

}
Arrays in original order: [45, 12, 78, 34, 67, 10, 55, 44]
Sorted arrays in ascending order: [10, 12, 34, 44, 45, 55, 67, 78]

Similarly, we can also sort float, double, long, or char values using the sort() method.

import java.util.Arrays;

public class SortArray {

  public static void main(String[] args) {
    int[] arrNum = {45,12,78,34,67,10,55,44};
    char[] arrChar = {'v','d','a','r','j'};
    double[] arrDouble = {45.54,10.9,55.5,32.6,8.5};
    
    System.out.println("Arrays in original order: " + Arrays.toString(arrNum));
    System.out.println("Arrays in original order: " + Arrays.toString(arrChar));
    System.out.println("Arrays in original order: " + Arrays.toString(arrDouble));
    
    Arrays.sort(arrNum);
    Arrays.sort(arrChar);
    Arrays.sort(arrDouble);
    
    System.out.println("Sorted arrays in ascending order: " + Arrays.toString(arrNum));
    System.out.println("Sorted arrays in ascending order: " + Arrays.toString(arrChar));
    System.out.println("Sorted arrays in ascending order: " + Arrays.toString(arrDouble));

  }

}
Arrays in original order: [45, 12, 78, 34, 67, 10, 55, 44]
Arrays in original order: [v, d, a, r, j]
Arrays in original order: [45.54, 10.9, 55.5, 32.6, 8.5]
Sorted arrays in ascending order: [10, 12, 34, 44, 45, 55, 67, 78]
Sorted arrays in ascending order: [a, d, j, r, v]
Sorted arrays in ascending order: [8.5, 10.9, 32.6, 45.54, 55.5]

Sorting strings in Ascending order using the sort method

We can also sort an array of strings in ascending order using the sort methods of the Arrays class. The below example shows how to sort an array of strings in Java.

import java.util.Arrays;

public class SortArray {

  public static void main(String[] args) {
    String[] arrNames = {"Deepak","Susan","Aarthi","Chetan"};
    
    System.out.println("Arrays in original order: " + Arrays.toString(arrNames));
    
    Arrays.sort(arrNames);
    
    System.out.println("Sorted array in ascending order: " + Arrays.toString(arrNames));

  }

}
Arrays in original order: [Deepak, Susan, Aarthi, Chetan]

Sorted array in ascending order: [Aarthi, Chetan, Deepak, Susan]

Sort in ascending order using the for loop

We can also sort elements in ascending order without using the sort method. For this, we can use the for loop along with the swapping concept.

Algorithm:

  1. Initialize an array variable with integer values.
  2. Create an outer for loop that ranges from 0 to array length
  3. Create an inner for loop that ranges from i+1 to array length
  4. If first variable > second variable, then swap the two numbers using a temporary variable
  5. Repeat this process until end of loop.

Program:

public class SortArrayDemo {

  public static void main(String[] args) {
    int[] arrNum = {45,12,78,34,67,8};
    
    int temp = 0;
    System.out.println("Sorted array elements:");
    for(int i=0;i<arrNum.length;i++) {
      for(int j=i+1;j<arrNum.length;j++) {
        if(arrNum[i] > arrNum[j]) {
          temp = arrNum[i];
          arrNum[i] = arrNum[j];
          arrNum[j] = temp;
        }
      
      }
      System.out.println(arrNum[i]);
    }

  }

}
Sorted array elements:
8
12
34
45
67
78

Sort using a user-defined method

We can create our own logic in a user-defined method to sort the numeric values in ascending order. The below example shows how to sort an array in Java by creating our own method sort() to sort the values. We pass the array variable and length of the array to this method.

public class SortArrayDemo2 {

  public static void main(String[] args) {
    int[] arrNum = {55,11,66,22,88,33};
    sort(arrNum,arrNum.length);
    
    System.out.println("Sorted array elements:");
    for(int i=0;i<arrNum.length;i++) {
      System.out.println(arrNum[i]);
    }

  }
  
  public static void sort(int[] arr, int l) {
    for(int i=1;i<l;i++) {
      int j = i;
      int n = arr[i];
      
      while((j>0) && (arr[j-1] > n)) {
        arr[j] = arr[j-1];
        j--;
      }
      arr[j] = n;
    }
  }

}
Sorted array elements:
11
22
33
55
66
88

Sort using comparator

Apart from the above methods, we can also sort objects based on a particular value by implementing the Comparator interface as below. We mainly use this concept, when we want to sort an array of objects. In the below example, we are sorting elements based on the empID value.

import java.util.Arrays;
import java.util.Comparator;

class EmployeeData {
  int empId;
  String empName;
  
  public EmployeeData(int Id, String name) {
    this.empId = Id;
    this.empName = name;
  }
  
  public String toString() {
    return this.empId + " " + this.empName;
  }
  
}

class SortById implements Comparator<EmployeeData> {

  @Override
  public int compare(EmployeeData e1, EmployeeData e2) {
    // TODO Auto-generated method stub
    return e1.empId - e2.empId;
  }
  
}
public class SortMain {

  public static void main(String[] args) {
    EmployeeData[] emp = {new EmployeeData(444, "Dev"),
        new EmployeeData(111, "Arthi"),
        new EmployeeData(555, "Jai")};
    
    Arrays.sort(emp, new SortById());
    
    System.out.println("Sorted order:");
    for(int i=0;i<emp.length;i++) {
      System.out.println(emp[i]);
    }

  }

}
Sorted order:
111 Arthi
444 Dev
555 Jai

Sort in descending order

Now that we have seen how to sort an array in Java in ascending order, let us see the different ways to sort an array in descending order. This means, it orders the elements starting from high value and ends with a low value.

  • Arrays.reverse() method
  • Without using the sort method
    •  for loop
    • user-defined method
    • comparator

Collections.reverseOrder() – descending sort

The sort method of the Arrays class also sorts elements in descending order by using the Collections.reverseOrder as a parameter. Below is an example that uses the reverseOrder() to sort in descending order.

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

public class SortArray {

  public static void main(String[] args) {
    Integer[] arrNum = {45,12,78,34,67,10,55,44};
    
    System.out.println("Arrays in original order: " + Arrays.toString(arrNum));
    
    Arrays.sort(arrNum, Collections.reverseOrder());

    System.out.println("Sorted array in descending order: " + Arrays.toString(arrNum));
  }

}
Arrays in original order: [45, 12, 78, 34, 67, 10, 55, 44]
Sorted array in descending order: [78, 67, 55, 45, 44, 34, 12, 10]

Using for loop

The below example shows how to sort elements in an array in descending order by using a for loop.

public class SortArrayDemo {

  public static void main(String[] args) {
    int[] arrNum = {45,12,78,34,67,8};
    
    
    int temp = 0;
    System.out.println("Sorted array elements in descending order:");
    for(int i=0;i<arrNum.length;i++) {
      for(int j=i+1;j<arrNum.length;j++) {
        if(arrNum[i] < arrNum[j]) {
          temp = arrNum[i];
          arrNum[i] = arrNum[j];
          arrNum[j] = temp;
        }
      
      }
      System.out.println(arrNum[i]);
    }

  }

}
Sorted array elements in descending order:
78
67
45
34
12
8

Reference

Translate »