Java
Sorting
Array
Programming
Algorithms

Sort an array in Java

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

In Java, sorting an array is usually a library problem, not an algorithm-writing problem. The main choice is which Arrays.sort overload matches your data: primitive values, objects with natural ordering, or objects sorted by a custom comparator.

Sort Primitive Arrays with Arrays.sort

For numeric and other primitive arrays, the standard answer is Arrays.sort(array). It sorts the array in place, which means the original array is modified rather than a new array being returned.

java
1import java.util.Arrays;
2
3public class PrimitiveSortDemo {
4    public static void main(String[] args) {
5        int[] numbers = {42, 7, 19, 3, 15};
6        Arrays.sort(numbers);
7        System.out.println(Arrays.toString(numbers));
8    }
9}

This is the normal production approach for ascending order. It is clearer and safer than reimplementing bubble sort, quicksort, or insertion sort by hand.

If you need only a portion of the array sorted, Java also provides range-based overloads. That can be useful when the array contains a sorted prefix and an unsorted working region.

Sort Object Arrays by Natural Order

Object arrays can also use Arrays.sort as long as the element type already has a natural ordering. Strings are a common example.

java
1import java.util.Arrays;
2
3public class StringSortDemo {
4    public static void main(String[] args) {
5        String[] fruits = {"Banana", "Apple", "Pear"};
6        Arrays.sort(fruits);
7        System.out.println(Arrays.toString(fruits));
8    }
9}

Here Java uses the compareTo implementation on String. The same rule applies to any class that implements Comparable.

Use a Comparator for Custom Ordering

When the natural order is not what you need, pass a comparator. This is the usual answer for descending order or sorting by one field of a custom class.

java
1import java.util.Arrays;
2import java.util.Comparator;
3
4class User {
5    final String name;
6    final int age;
7
8    User(String name, int age) {
9        this.name = name;
10        this.age = age;
11    }
12
13    @Override
14    public String toString() {
15        return name + ":" + age;
16    }
17}
18
19public class ComparatorSortDemo {
20    public static void main(String[] args) {
21        User[] users = {
22            new User("Ana", 30),
23            new User("Ben", 24),
24            new User("Cara", 27)
25        };
26
27        Arrays.sort(users, Comparator.comparingInt(user -> user.age));
28        System.out.println(Arrays.toString(users));
29    }
30}

This keeps the sort rule close to the call site, which is often easier to maintain than embedding one global natural order into the class.

Descending Order and the Primitive Trap

A common source of confusion is that comparator-based sorting works only with object arrays, not primitive arrays. That means this works:

java
1import java.util.Arrays;
2import java.util.Comparator;
3
4public class ReverseIntegerDemo {
5    public static void main(String[] args) {
6        Integer[] values = {5, 1, 9, 3};
7        Arrays.sort(values, Comparator.reverseOrder());
8        System.out.println(Arrays.toString(values));
9    }
10}

But the same approach does not work with int[]. If you need descending order for primitives, the simplest options are either to sort ascending and reverse manually or to store boxed values in Integer[] and use a comparator.

Prefer the Standard Library Over Hand-Written Sorts

Interview exercises often encourage implementing classic sorting algorithms. That is useful for learning time complexity, but it is rarely the correct answer in application code.

java
1import java.util.Arrays;
2
3public class RangeSortDemo {
4    public static void main(String[] args) {
5        int[] numbers = {9, 4, 7, 1, 8, 3};
6        Arrays.sort(numbers, 1, 5);
7        System.out.println(Arrays.toString(numbers));
8    }
9}

Using the standard library gives you tested behavior, better readability, and less maintenance risk. Unless you are writing a specialized low-level library, custom sort implementations are usually wasted effort.

Common Pitfalls

  • Rewriting sorting algorithms manually when Arrays.sort already solves the problem.
  • Forgetting that sorting happens in place and mutates the original array.
  • Trying to use a comparator with a primitive array such as int[].
  • Sorting custom objects without defining a comparator or Comparable implementation.
  • Converting arrays to lists only to sort them, even though the array API already supports the needed operation.

Summary

  • Use Arrays.sort for nearly all array sorting in Java.
  • Primitive arrays use Arrays.sort(array) for ascending order.
  • Object arrays can use natural ordering or a custom comparator.
  • Descending comparator-based sorting requires object arrays such as Integer[].
  • Prefer the standard library over hand-written sorting code in production.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.