1、Arrays.sort(數組名)
對數組中的所有元素進行排序,並且是按照從小到大的順序進行的。
Integer[] test = new Integer[n]; Arrays.sort(test);
2、Arrays.sort(數組名,起始下標,終止下標)
對數組中的部分元素進行排序,即從起始下標到終止下標-1的元素排序。
3、使用比較器比較的方法
public class t6 { static int n; public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入個數:"); int n = sc.nextInt(); Integer[] test = new Integer[n]; for(int i = 0; i < n; i++) { test[i] = sc.nextInt(); } MyComparator cmp = new MyComparator(); Arrays.sort(test, cmp); for(Integer p: test) { System.out.println(p); } } } class MyComparator implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return o1 - o2; //從小到大 } }
class MyComparator implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { if(o1 > o2) { return 1; }else if (o1 < o2) { return -1; }else { return 0; } } }
class MyComparator implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return o2 - o1; //從大到小 } }
class MyComparator implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { if(o1 < o2) { return 1; }else if (o1 > o2) { return -1; }else { return 0; } } }