1. 程式人生 > >計數排序Java示例

計數排序Java示例

計數排序是一個非基於比較的排序演算法,計數排序的基本思想是:對於給定的輸入序列中的每一個元素x,確定該序列中值小於x的元素的個數。有了這個資訊之後,就可以將x直接存放到最終的輸出序列的正確位置上。例如,如果輸入序列中只有10個元素的值小於x的值,則x可以直接存放在輸出序列的第11個位置上。

演算法過程:

假設輸入的線性表L的長度為n,L=L1,L2,..,Ln;線性表的元素屬於有限偏序集S,|S|=k且k=O(n),S={S1,S2,..Sk};則計數排序可以描述如下: 1、掃描整個集合S,對每一個Si∈S,找到線上性表L中小於等於Si的元素的個數T(Si); 2、掃描整個線性表L,對L中的每一個元素Li,將Li放在輸出線性表的第T(Li)個位置上,並將T(Li)減1。

java示例:

public class CountSort {

    public static void main(String[] args) {
        //排序的陣列
        int[] arr = {1,3,2,6,3,66,33,65,33,67,45,77,78,36,56};
        System.out.println("排序前:");
        System.out.println(Arrays.toString(arr));
        int result[] = sort(arr);
        System.out.println("排序後:");
        System.out.println(Arrays.toString(result));
    }

    public static int[] sort(int[] arr) {
        int result[] = new int[arr.length];
        int max = arr[0], min = arr[0];
        for (int i : arr) {
            if (i > max) {
                max = i;
            }
            if (i < min) {
                min = i;
            }
        }
        int k = max - min + 1;//這裡k的大小是要排序的陣列中,元素大小的極值差+1
        int temp[] = new int[k];
        for (int i = 0; i < arr.length; ++i) {
            temp[arr[i] - min]++;
        }
        for (int i = 1; i < temp.length; ++i) {
            temp[i] += temp[i - 1];
        }
        for (int i = arr.length - 1; i >= 0; --i) {
            result[--temp[arr[i] - min]] = arr[i];//按存取的方式取出temp的元素
        }
        return result;
    }
}

執行結果:

排序前:
[1, 3, 2, 6, 3, 66, 33, 65, 33, 67, 45, 77, 78, 36, 56]
排序後:
[1, 2, 3, 3, 6, 33, 33, 36, 45, 56, 65, 66, 67, 77, 78]

Process finished with exit code 0