Java
Sorting Algorithms
Java.util
Arrays
Programming

Sorting algorithm of Arrays in Java.util package

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

java.util.Arrays does not use one universal sorting algorithm for all array types. Primitive arrays and object arrays are handled differently, and parallel sorting has its own tradeoffs. Understanding these differences helps you choose the right method and avoid false assumptions about stability and performance.

Primitive Arrays and Arrays.sort

For primitive arrays, Arrays.sort uses an in-place dual-pivot quicksort in modern JDKs.

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

Important characteristics:

  • In-place behavior.
  • Average O(n log n) complexity.
  • Not stable for equal primitive values, which usually matters only when external identity is tracked.

For basic numeric arrays, this is the standard default.

Object Arrays and Stable Sorting

Object-array sorting uses a stable algorithm with comparator support.

java
1import java.util.Arrays;
2import java.util.Comparator;
3
4class Row {
5    final String group;
6    final int score;
7
8    Row(String group, int score) {
9        this.group = group;
10        this.score = score;
11    }
12
13    @Override
14    public String toString() {
15        return group + ":" + score;
16    }
17}
18
19public class ObjectSortDemo {
20    public static void main(String[] args) {
21        Row[] rows = {
22            new Row("A", 90),
23            new Row("B", 90),
24            new Row("A", 80)
25        };
26
27        Arrays.sort(rows, Comparator.comparingInt(r -> r.score));
28        Arrays.sort(rows, Comparator.comparing(r -> r.group));
29
30        System.out.println(Arrays.toString(rows));
31    }
32}

Stable sorting preserves relative order of equal keys, which is useful in multi-step ordering workflows.

Comparator Design Matters

In object sorting, comparator cost can dominate runtime. Keep comparators cheap and deterministic.

Good pattern:

java
Arrays.sort(rows, Comparator
        .comparing((Row r) -> r.group)
        .thenComparingInt(r -> r.score));

Avoid expensive operations inside comparator calls, such as regex parsing or network lookups.

Arrays.parallelSort Tradeoffs

Arrays.parallelSort can improve performance on large arrays by using multiple threads.

java
1import java.util.Arrays;
2
3public class ParallelSortDemo {
4    public static void main(String[] args) {
5        int[] data = new int[2_000_000];
6        for (int i = 0; i < data.length; i++) {
7            data[i] = data.length - i;
8        }
9
10        Arrays.parallelSort(data);
11        System.out.println(data[0] + " ... " + data[data.length - 1]);
12    }
13}

For small arrays, overhead can outweigh benefits. Benchmark before adopting parallel sort globally.

Benchmarking Strategy

To compare sort methods fairly:

  • Warm up the JVM.
  • Use realistic data distributions.
  • Run multiple iterations.
  • Measure end-to-end use case, not only isolated sort call.

Single-shot timing often misleads because JIT and cache behavior dominate early runs.

Selecting the Right Method

Practical rules:

  • Primitive arrays: start with Arrays.sort.
  • Very large arrays: compare sort and parallelSort on target hardware.
  • Object arrays with custom order: Arrays.sort with explicit comparator chain.
  • Multi-key ordering: use thenComparing or stable multi-pass approach.

Correctness and comparator quality usually matter more than algorithm micro-details.

Stability and Multi-Key Workflows

When processing business records, stability affects correctness for chained sorts. For object arrays, stable sorting allows secondary-key sorts to be applied first and preserved by later primary-key sorts. For primitive arrays, stability is usually irrelevant because values carry no extra attached identity, but for boxed or custom object types it can change result interpretation in reporting pipelines.

Common Pitfalls

  • Assuming all array sorts in Arrays are stable.
  • Writing comparators that violate transitivity and break ordering.
  • Using parallelSort for small arrays and slowing performance.
  • Ignoring comparator cost while tuning sort performance.
  • Benchmarking without JVM warmup and drawing incorrect conclusions.

Summary

  • 'Arrays.sort behavior differs for primitives and objects.'
  • Primitive sorting is in-place and fast, but not stable.
  • Object sorting supports stable ordering with comparators.
  • 'Arrays.parallelSort helps mainly for large workloads on multi-core systems.'
  • Comparator correctness and realistic benchmarking are critical for reliable sort decisions.

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.