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

Image of PulumiUP 2025

From Cloud to Platforms: What Top Engineers Are Doing Differently

Hear insights from industry leaders about the current state and future of cloud and IaC, platform engineering, and security.

Save Your Spot

Top comments (0)

PulumiUP 2025 image

PulumiUP 2025: Cloud Innovation Starts Here

Get inspired by experts at PulumiUP. Discover the latest in platform engineering, IaC, and DevOps. Keynote, demos, panel, and Q&A with Pulumi engineers.

Register Now

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay