冒泡算法和直接算法的效率對比

 

public class ArrayDemo07 {

    public static void main(String args[]) {

        int score[] = { 77, 89, 87, 69, 90, 100, 75, 90 }; // 使用靜態初始化聲明數組

        int score1[] = { 77, 89, 87, 69, 90, 100, 75, 90 }; // 使用靜態初始化聲明數組

        long startTime1 = System.nanoTime();

        for (int i = 1; i < score.length; i++) {

            for (int j = 0; j < score.length; j++) {

                if (score[i] < score[j]) { // 交換位置

                    int temp = score[i]; // 中間變量

                    score[i] = score[j];

                    score[j] = temp;

                }

            }

        }

        long endTime1 = System.nanoTime();

        long time1 = endTime1 - startTime1;

        System.out.println("冒泡算法所需時間:" + time1 + "納秒.");

        for (int x : score) {

            System.out.print(x + "\t");

        }

        System.out.println();

        long startTime2 = System.nanoTime();

        for (int i = 0; i < score1.length; i++) {

            for (int j = i + 1; j < score1.length; j++) {

                if (score1[i] > score1[j]) { // 交換位置

                    int temp = score1[j]; // 中間變量

                    score1[j] = score1[i];

                    score1[i] = temp;

                }

            }

        }

        long endTime2 = System.nanoTime();

        long time2 = endTime2 - startTime2;

        System.out.println("直接算法所需時間:" + time2 + "納秒.");

        for (int x : score1) {

            System.out.print(x + "\t");

        }

        System.out.println();

    }

};

 

程序運行結果:

冒泡算法所需時間:3158納秒.
69    75    77    87    89    90    90    100    
直接算法所需時間:1974納秒.
69    75    77    87    89    90    90    100

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章