题解 | 输入整型数组和排序标识,对其元素按照升序或降序进行排序
解题思路:
- 这是一个入门题
- 随便使用一个排序算法就可以了,在排序判断是,增加一下排序规则就可以了
- 需要注意点是:in.next(),in.nextLine()的区别,否则可能无法读取到数据
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = Integer.parseInt(in.nextLine()); String[] s = in.nextLine().split(" "); int order = in.nextInt(); for (int i = 0; i < n; i++) { int tmp = Integer.parseInt(s[i]); int j = i - 1; boolean flag; while (j >= 0 && customOrder(Integer.parseInt(s[j]), tmp, order)) { s[j + 1] = s[j]; j--; } s[j + 1] = tmp + ""; } System.out.println(String.join(" ", s)); } public static boolean customOrder(int i, int j, int order) { if (order == 0) { return i > j; } return j > i; } }