關於常用的排序算法

常用的排序算法

排序算法 平均時間複雜度
冒泡排序 O(n2)
選擇排序 O(n2)
插入排序 O(n2)
希爾排序 O(n1.5)
快速排序 O(N*logN)
歸併排序 O(N*logN)
堆排序 O(N*logN)
基數排序 O(d(n+r))

冒泡排序

所謂冒泡排序 就是比較兩個相鄰的數,大的下沉小的上浮,這種方法時間複雜度爲O(n^2),如果數量級比較高,不適宜用這種方法

public static void MaoPao(){
        int[] a = {5,3,2,3,1,2,3,1};
        int temp;
        for (int i = 0; i < a.length-1; i++) {
            for(int j=a.length-1; j>i; j--){

                if(a[j] < a[j-1]){
                    temp = a[j];
                    a[j] = a[j-1];
                    a[j-1] = temp;
                }
            }
        }
        for (int i = 0; i < a.length; i++) {
            Log.e("MaoPao result",""+a[i]);
        }
    }

選擇排序

遍歷整個數據找出最大/最小的放到第一個,反覆執行這一操作,將數據排序,平均時間複雜的也是O(n^2)

 public static void XuanZe(){
        int[] a = {3,9,5,8,6,4,7,1,2};
        int lenth = a.length;
        for(int i=0;i<lenth-1;i++){

            int minIndex = i;
            for(int j=i+1;j<lenth;j++){
                if(a[j]<a[minIndex]){
                    minIndex = j;
                }
            }
            if(minIndex != i){
                int temp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = temp;
            }
        }

        for (int i = 0; i < a.length; i++) {
            Log.e("XuanZe result",""+a[i]);
        }

    }

插入排序

把整個數組分成兩部分,一部分排過序,一部分沒有,然後把沒有排過序的一個一個插入到對應位置,時間複雜度依然是

public static void ChaRu(){
        int[] a = {3,9,5,8,6,4,7,1,2};
        int lenth = a.length;

        int temp;

        for(int i=0;i<lenth-1;i++){
            for(int j=i+1;j>0;j--){
                if(a[j] >= a[j-1]){
                    break;
                }

                temp = a[j-1];
                a[j-1] = a[j];
                a[j] = temp;
            }
        }


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