Respuesta :
Answer:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null) {
int numberOfElements = Integer.parseInt(s);
s = in.readLine();
StringTokenizer st = new StringTokenizer(s);
ArrayList<Integer> array = new ArrayList<>();
while (numberOfElements-- > 0) {
array.add(Integer.parseInt(st.nextToken()));
}
System.out.println(sortArray(array));
}
}
public static ArrayList<Integer> sortArray(ArrayList<Integer> array) {
Collections.sort(array);
Collections.reverse(array);
return array;
}
}
Explanation:
You could simply define an array in such a way that it can store up to 20 elements, however, it's always preferred to use an ArrayList since you can add elements on the go, and will not have to ignore the resting "0" values initialized in an array when the number of elements in the input is lower than 20.
You simply read the line which contains the number of elements, then read the next line which contains the input of the numbers you want to sort in descending order.
For this, I made a while loop that takes the number of elements and parses them into the ArrayList, by adding each one individually.
Then, I call the method sortArray" which uses Collections.sort() to sort the array. That, however, will sort the array in ascending order, not descending order. So that's why I included the Collections.reverse(), which takes the sorted array, and simply orders it in reverse (descending order).
The program should work as specified. Nonetheless, your problem statement did not include any input or output samples, so I assumed it is like the following:
Input
5
10 20 12 521 37
Output
[521, 37, 20, 12, 10]