Java數組排序


一、sort()進行排序

  升序:

public class Main {

    public static void main(String[] args) {
        int[] scores = new int[] {3,1,5,6,4};
        for (int i = 0;i<scores.length;i++){
            System.out.println(scores[i]);
        }
        Arrays.sort(scores);
        for (int j = 0;j<scores.length;j++){
            System.out.println(scores[j]);
        }

    }
}

  降序:

  •   Collections.reverseOrder()方法
public class Main {

    public static void main(String[] args) {
        Integer[] a = {3,4,5,1,2};
        Arrays.sort(a, Collections.reverseOrder());
        for (int i = 0;i<a.length;i++){
            System.out.println(a[i]);
        }
    }
}
  • 實現 Comparator 接口的復寫 compare() 方法
public class Main {

    public static void main(String[] args) {
        Integer[] a = {3,4,5,1,2};
        Comparator cmp = new MyComparator();
        Arrays.sort(a, cmp);
        for (int i = 0;i<a.length;i++){
            System.out.println(a[i]);
        }
    }

}
class MyComparator implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        return o2 - o1;
    }
}

二、冒泡排序

  排序思路:比較數組兩個相鄰的元素,如果滿足條件就交換元素,把較小的元素移至數組前面,較大的元素移至數組后面,這樣較大元素會像氣泡一樣上升至頂部。

 

public class Demo01 {
    public static void main(String[] args) {
        double[] score = {6,1,5,3,4};
        for (int i = 0; i < score.length - 1; i++) {
            // 比較相鄰兩個元素,較大的數往后冒泡
            for (int j = 0; j < score.length - 1 - i; j++) {
                if (score[j] > score[j + 1]) {
                    double temp = score[j + 1]; // 把第一個元素值保存到臨時變量中
                    score[j + 1] = score[j]; // 把第二個元素值轉移到第一個元素變量中
                    score[j] = temp; // 把臨時變量(第一個元素的原值)保存到第二個元素中
                }
                System.out.print(score[j] + " "); // 對排序后的數組元素進行輸出
            }
            for (int j = score.length - 1 - i; j < score.length; j++) {
                System.out.print(score[j] + " ");
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM