Home > Java > javaTutorial > How to Sort an Array in Reverse Order in Java?

How to Sort an Array in Reverse Order in Java?

DDD
Release: 2024-11-03 01:50:03
Original
939 people have browsed it

How to Sort an Array in Reverse Order in Java?

Sorting an Array in Reverse

Many programming languages provide convenient functions for sorting arrays in ascending order. However, the question arises: Is there a similar approach for sorting arrays in descending order?

Java's Arrays Class

In Java, the Arrays class offers the sort() method for sorting arrays. However, this method lacks direct support for descending order. One option is to use a Comparator to define the reverse order of elements.

Using a Comparator

Arrays.sort() allows you to specify a Comparator to determine the sorting order. The Collections class provides the reverseOrder() method to create a Comparator that inverts the natural ordering.

Arrays.sort(a, Collections.reverseOrder());
Copy after login

This approach works for sorting arrays of objects, such as Integer arrays. However, it fails for primitive arrays, such as int arrays.

Alternative for Primitive Arrays

To sort primitive arrays in descending order, one must first sort them in ascending order using Arrays.sort() and then manually reverse the array elements.

Arrays.sort(a);
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}
Copy after login

By employing these techniques, it is possible to sort an array in descending order, whether it contains objects or primitives.

The above is the detailed content of How to Sort an Array in Reverse Order in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template