排序算法之計數排序【Java版】

引言

本篇是排序算法的第七篇,計數排序。

1、算法步驟

1、將待排序的數組裏的值,作爲新數組中的下標;
2、新數組下標中對應的值重複的計數累加;
3、最後新數組中下標有值的依次放到數組中(下標本身已經排好序了)。

2、時間複雜度

平均時間複雜度O(n + k)

3、算法實現

public class CountSort {
    public static void main(String[] args) {
        int[] numbers = {12,2,24,30,6,16};
        int[] result = CountSort.sort(numbers);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < result.length; i++) {
            stringBuffer.append(result[i] + " ");
        }
        System.out.println(stringBuffer.toString());
    }

    public static int[] sort(int[] number){
        //重新copy一個新數組,不影響參數
        int[] arg = Arrays.copyOf(number, number.length);
        //獲取最大數組下標
        int maxValue = getMaxValue(arg);
        return counting(maxValue,arg);
    }

    public static int[] counting(int max,int[] arg){
        //初始化一個新數組
        int[] newArray = new int[max + 1];
        //統計下標值次數
        for (int value : arg){
            newArray[value]++;
        }
        int index = 0;
        for (int i = 0; i < newArray.length; i++) {
            while (newArray[i] > 0){
                //下標是順序的,有值,則放入之前的數組
                arg[index++] = i;
                //計數相應的減少1
                newArray[i]--;
            }
        }
        return arg;
    }

    public static int getMaxValue(int[] arg){
        int maxValue = arg[0];
        for (int i = 1; i < arg.length; i++) {
            if(maxValue < arg[i]){
                maxValue = arg[i];
            }
        }
        return maxValue;
    }
}

結束語

計數算法對空間要求度高,排序中如果數據量小,有數據值特別大,那對空間是極大的浪費。

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