Title description
Enter an integer array and sort identifier, and sort its elements in ascending or descending order (a set of test cases may have multiple sets of data)
There are multiple sets of input for this question, please use while(cin>>) to process
Example
enter
8
1 2 4 9 3 55 64 25
0
5
1 2 3 4 5
1
Output
1 2 3 4 9 25 55 64
5 4 3 2 1
analysis
1. According to the requirements of the title, enter 3 sets of data, the first set is the number of data in the second set, and the third set judges whether it is output in positive or reverse order
2. For positive order, directly call the sort method in Arrays. For reverse order, write a method, you can use bubbling, or you can sort it in positive order, and then exchange the first and last positions, and then reach the reverse order. effect
Code
import java.util.Arrays;
import java.util.Scanner;
public class Main3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int num = sc.nextInt();
int[] arr = new int[num];
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
int p = sc.nextInt();
if (p == 0) {
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++)
if (i != (arr.length - 1))
System.out.print(arr[i] + " ");
else
System.out.print(arr[i]);
} else {
S(arr);
for (int i = 0; i < arr.length; i++)
if (i != (arr.length - 1))
System.out.print(arr[i] + " ");
else
System.out.print(arr[i]);
}
}
}
public static void S(int[] arr) {
Arrays.sort(arr);
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
}
}