Java program to sort array using Collections reverseOrder method

Program

import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;
public class SortArrayInReversseOrderUsingCollections {
  public static void main(String[] args) {
    int i = 0;
    System.out.println("Enter the required size of the array: ");
    Scanner reader = new Scanner(System.in);
    int size = reader.nextInt();
    Integer inputArray[] = new Integer[size];
    System.out.println("Enter the elements of the array: ");
    for (i = 0; i < size; i++) {
      inputArray[i] = reader.nextInt();
    }
    Arrays.sort(inputArray, Collections.reverseOrder()); 
    System.out.println("Array elements sorted in decending order: ");
    System.out.println(Arrays.toString(inputArray));
  }
}

This program demonstrates sorting an array in descending (reverse) order using the Collections.reverseOrder() method.

  1. Input Handling:

    • The program prompts the user to input the size of the array.
    • It then allows the user to enter the elements of the array.
  2. Sorting Logic:

    • The Arrays.sort() method is used with Collections.reverseOrder() as a comparator.
    • This sorts the array in descending order.
  3. Output:

    • The sorted array in reverse order is printed using Arrays.toString().
  4. Key Note:

    • The array must be of the Integer type (not int) for Collections.reverseOrder() to work, as it requires objects, not primitive types.

Example:

Input:

  • Array size: 5
  • Array elements: 30 10 50 20 40

Process:

  • Sort in descending order: 50 40 30 20 10

Output:

  • Sorted array: [50, 40, 30, 20, 10]

Key Features:

  1. Simple Sorting:
    • Sorting is done in a single step using a built-in method.
  2. Efficient for Small Arrays:
    • Suitable for arrays where reverse ordering is needed quickly.
  3. Ease of Use:
  • Utilizes Java's built-in libraries for simplicity and readability.
  1. Reusability:
  • The logic can be easily adapted for other object arrays (e.g., String[]).

Output

javac .\SortArrayInReversseOrderUsingCollections.java
java SortArrayInReversseOrderUsingCollections        
Enter the required size of the array: 
5
Enter the elements of the array: 
10
20
40
60
30
Array elements sorted in decending order: 
[60, 40, 30, 20, 10]