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.
-
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.
-
Sorting Logic:
- The
Arrays.sort()
method is used withCollections.reverseOrder()
as a comparator. - This sorts the array in descending order.
- The
-
Output:
- The sorted array in reverse order is printed using
Arrays.toString()
.
- The sorted array in reverse order is printed using
-
Key Note:
- The array must be of the
Integer
type (notint
) forCollections.reverseOrder()
to work, as it requires objects, not primitive types.
- The array must be of the
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:
- Simple Sorting:
- Sorting is done in a single step using a built-in method.
- Efficient for Small Arrays:
- Suitable for arrays where reverse ordering is needed quickly.
- Ease of Use:
- Utilizes Java's built-in libraries for simplicity and readability.
- 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]