DEV Community

loizenai
loizenai

Posted on

How to Sort an Array in Java with Examples

https://grokonez.com/java/how-to-sort-an-array-in-java-tutorial-with-example

How to Sort an Array in Java with Examples

In the tutorial, we will discuss how to Sort an Array with Java in ascending and descending order. java.util.Arrays class provides a lot of Methods to sort an Array with difference types:

  • With Primitives Array, We use the method such as: static void sort(int[] a).
  • With String or Objects Array that implement Comparable, We use method: static void sort(Object[] a).
  • With Custom Object Array that no implement Comparable, We use method: sort(T[] a, Comparator super T> c).

Let's do more details with Java Array Sorting.

Sort with Primitives Java Array

We define a simple Int Java Array:


int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 };

Sorting in Ascending Order

We use the method static void sort(int[] a) to sort the specified array into ascending numerical order.

  • The method returns nothing
  • The Sorting algorithm is a Dual-Pivot Quicksort
  • This algorithm offers O(n log(n)) performance so it is typically faster than traditional (one-pivot) Quicksort implementations.

Practice:

package com.grokonez.sortarray;

import java.util.Arrays;

public class JavaArraySortingExample {
    public static void main(String[] args) {
        int[] numbers = new int[] { -9, 5, 4, 8, 11, -2, 2 };
        
        // Sorting
        Arrays.sort(numbers);
        
        // Print Sorted-Array after Sorting
        for(int i=0; i<numbers.length; i++) {
            System.out.println(numbers[i]); 
        }
    }
}

Output:


// Output
-9
-2
2
4
5
8
11

Sorting in Descending Order

Java doesn’t support the use of Comparators on primitive types so sorting a primitive array in descending order is not easy.

More:

https://grokonez.com/java/how-to-sort-an-array-in-java-tutorial-with-example

How to Sort an Array in Java with Examples

Top comments (0)