Home > Java > javaTutorial > body text

How to Sort a Java Array in Descending Order?

Linda Hamilton
Release: 2024-11-02 00:10:31
Original
906 people have browsed it

How to Sort a Java Array in Descending Order?

Java Array Sort in Descending Order

An array sorting utility exists in the Arrays class to sort arrays in ascending order. However, there isn't a direct method to sort arrays in descending order.

Solution Using Comparator

To sort an array of objects in descending order, use the following code:

<code class="java">sort(T[] a, Comparator<? super T> c)</code>
Copy after login
<code class="java">Arrays.sort(a, Collections.reverseOrder());</code>
Copy after login

Solution for Primitive Arrays

For primitive arrays like int[], the above method won't work directly. Instead, follow these steps:

  1. Sort the array in ascending order:

    <code class="java">Arrays.sort(a);</code>
    Copy after login
  2. Reverse the sorted array in place:

    <code class="java">reverseArray(a);
    
    private static void reverseArray(int[] arr) {
      for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
     int temp = arr[i];
     arr[i] = arr[j];
     arr[j] = temp;
      }
    }</code>
    Copy after login

Example

<code class="java">public static void main(String[] args) {
  int[] arr = {5, 3, 1, 2, 4};

  // Sort in descending order
  reverseArray(arr);

  // Print the sorted array
  for (int num : arr) {
    System.out.println(num); // 5, 4, 3, 2, 1
  }
}</code>
Copy after login

The above is the detailed content of How to Sort a Java Array in Descending Order?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!