Sort an array in Java

66    Asked by uasham_1987 in Java , Asked on May 11, 2025

How do you sort an array in Java? Learn the different ways to arrange elements in ascending or descending order using built-in methods like Arrays.sort() or custom sorting techniques in Java.

Answered by Jiten Testing

Sorting an array in Java is a common task and can be accomplished easily using built-in methods or custom sorting techniques. Below are the different ways you can sort an array in Java:

1. Using Arrays.sort() for Ascending Order:

The simplest way to sort an array in Java is by using the Arrays.sort() method, which sorts the elements in ascending order by default.

import java.util.Arrays;
int[] numbers = {5, 3, 8, 1, 2};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 5, 8]

This method works for arrays of primitive types (like int, char, etc.) as well as objects.

2. Sorting in Descending Order:

To sort in descending order, you can use a custom comparator if you are working with objects or reverse the array after sorting:

import java.util.Arrays;
import java.util.Collections;
Integer[] numbers = {5, 3, 8, 1, 2};
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println(Arrays.toString(numbers)); // Output: [8, 5, 3, 2, 1]

Note that for primitive types like int[], you can sort them in descending order by using a workaround (like sorting in ascending order and then reversing).

3. Using Custom Sorting (Comparator):

If you're working with objects or need a custom sorting order, you can define your own comparator:

import java.util.Arrays;
import java.util.Comparator;
String[] words = {"apple", "banana", "cherry"};
Arrays.sort(words, Comparator.reverseOrder());
System.out.println(Arrays.toString(words)); // Output: [cherry, banana, apple]

Why Sort Arrays?

  • Sorting is useful for searching algorithms (like binary search) or when presenting data in a specific order.
  • It's a fundamental operation in programming and helps optimize code efficiency in many scenarios.



Your Answer

Interviews

Parent Categories