java题目 HJ101 输入整型数组和排序标识,对其元素按照升序或

 

描述

输入整型数组和排序标识,对其元素按照升序或降序进行排序
 
数据范围: 1 \le n \le 1000 \1n1000  ,元素大小满足 0 \le val \le 100000 \0val100000 

输入描述:

第一行输入数组元素个数
第二行输入待排序的数组,每个数用空格隔开
第三行输入一个整数0或1。0代表升序排序,1代表降序排序

输出描述:

输出排好序的数字

示例1

输入:
8
1 2 4 9 3 55 64 25
0
输出:
1 2 3 4 9 25 55 64

示例2

输入:
5
1 2 3 4 5
1
输出:
5 4 3 2 1

 

 1 import  java.io.*;
 2 import java.util.*;
 3 
 4 public class Main {
 5     public static void main(String[] args) throws IOException {
 6         Scanner sc = new Scanner(System.in);
 7         
 8         while(sc.hasNext()) {
 9             int n = sc.nextInt();
10             List<Integer> list = new ArrayList<>();
11             for(int i =0; i<n; i++) {
12 //                 list[i] = sc.nextInt();
13                 list.add(sc.nextInt());
14             }
15             
16             if(sc.nextInt() == 0) {
17                 list.sort(Comparator.naturalOrder());
18             } else {
19                 list.sort(Comparator.reverseOrder());
20             }
21 //             if(sc.nextInt() == 0) {
22 //                 Arrays.sort(list, new Comparator<Integer>() {
23 //                     @Override
24 //                     public int compare(Integer o1, Integer o2) {
25 //                         return o1 - o2;
26 //                     }
27 //                 });
28 //             } else {
29 //                     Arrays.sort(list, new Comparator<Integer>() {
30 //                     @Override
31 //                     public int compare(Integer o1, Integer o2) {
32 //                         return o2 - o1;
33 //                     }
34 //                 });
35 //             }
36 //             for(int i=0; i < list.length; i++) {
37 //                 System.out.print(list[i] + " ");
38 //             }
39             for(Integer i : list) {
40                 System.out.print(i + " ");
41             }
42         }
43     }
44 }

 

posted @ 2022-03-07 20:25  海漠  阅读(157)  评论(0编辑  收藏  举报