题解 | #整型数组按照升序或降序进行排序#
输入整型数组和排序标识,对其元素按照升序或降序进行排序
https://www.nowcoder.com/practice/dd0c6b26c9e541f5b935047ff4156309
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { StringBuffer bu = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String a; int[] chrAy; int i = 0, j, temp, l, n, way = 0; try { a = in.readLine(); n = parse(a); a = in.readLine(); chrAy = new int[n]; parseArr(a, chrAy); a = in.readLine(); way = a.charAt(0) - '0'; in.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } // 选择排序 l = chrAy.length; if (way == 0) { for (; i < l; i++) {// 升序 for (j = i + 1; j < l; j++) { if (chrAy[i] > chrAy[j]) { temp = chrAy[i]; chrAy[i] = chrAy[j]; chrAy[j] = temp; } } } } else { for (; i < l; i++) {// 降序 for (j = i + 1; j < l; j++) { if (chrAy[i] < chrAy[j]) { temp = chrAy[i]; chrAy[i] = chrAy[j]; chrAy[j] = temp; } } } } i = 0; for (; i < n; i++) { bu.append(chrAy[i] + " "); } System.out.print(bu); } static int parse(String a) { int i = 0, l = a.length(), n = 0; char[] chrAy = new char[l]; a.getChars(0, l, chrAy, 0); while (i < l) { if ((chrAy[i] - '0' | '9' - chrAy[i]) > 0) { n *= 10; n += chrAy[i] - '0'; } i++; } return n; } static void parseArr(String a, int[] ins) { int i = 0, j = 0, l = a.length(), n = 0; char[] chrAy = new char[l]; a.getChars(0, l, chrAy, 0); while (i < l) { if (chrAy[i] == ' ') { ins[j++] = n; n = 0; } else { n *= 10; n += chrAy[i] - '0'; } if (i == l - 1) { ins[j++] = n; } i++; } } }