输入整型数组和排序标识,对其元素按照升序或降序进行排序
输入整型数组和排序标识,对其元素按照升序或降序进行排序
http://www.nowcoder.com/questionTerminal/dd0c6b26c9e541f5b935047ff4156309
简单使用Comparator
import java.util.*; public class Main { public Main() { } public void sortIntegerArray(Integer[] pIntegerArray, int iSortFlag) { // 按升序 if (iSortFlag == 0) { Arrays.sort(pIntegerArray, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1 - o2; } }); } // 按降序 else { Arrays.sort(pIntegerArray, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); } } public void output(Integer[] array) { for (Integer i : array) { System.out.print(i + " "); } System.out.println(); } public static void main(String[] args) { Main solution = new Main(); Scanner in = new Scanner(System.in); while (in.hasNextInt()) { int n = in.nextInt(); Integer[] array = new Integer[n]; for (int i = 0; i < n; i++) { array[i] = in.nextInt(); } int flag = in.nextInt(); solution.sortIntegerArray(array, flag); solution.output(array); } } }