排序算法之-------計數排序

Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence

Let us understand it with the help of an example.

For simplicity, consider the data in the range 0 to 9. 
Input data: 1, 4, 1, 2, 7, 5, 2
  1) Take a count array to store the count of each unique object.
  Index:     0  1  2  3  4  5  6  7  8  9
  Count:     0  2  2  0  1  1  0  1  0  0

  2) Modify the count array such that each element at each index 
  stores the sum of previous counts.(count[i] += count[i-1]) 
  Index:     0  1  2  3  4  5  6  7  8  9
  Count:     0  2  4  4  5  6  6  7  7  7

The modified count array indicates the position of each object in 
the output sequence.
 
  3) Output each object from the input sequence followed by 
  decreasing its count by 1.
  Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 2.
  Put data 1 at index 2 in output. Decrease count by 1 to place 
  next data 1 at an index 1 smaller than this index.

 Count each element in the given array and place the count at the appropriate index.

 Modify the count array by adding the previous counts.

Since we have seven input we create an array with seven places.

Corresponding values represent the places in the count array.

public class CountSort_1
{
    public static void countSort(int[] arr)
    {
        int len = arr.length;
        //output數組存儲arr數組的元素
        int[] output = new int[len];
        //Count數組存儲每個元素出現的次數
        int[] count = new int[256];
        for(int i=0; i<256; i++)
        {
            count[i] = 0;//初始化爲0
        }
        //數組中每個元素計數
        for(int i=0; i<len; i++)
        {
            ++count[arr[i]];//
        }
        for(int i=1; i<256; i++)
        {
            count[i] = count[i-1] + count[i];
        }
        // to make it stable, we operate in reverse order
        for(int i=len-1; i>=0; i--)
        {
            output[count[arr[i]] - 1] = arr[i];// - 1 是因爲數組的索引是從0開始的
            --count[arr[i]];
        }
        //複製output數組到arr數組中
        for(int i=0;i<len;i++)
            arr[i] = output[i];
    }
    public static void main(String[] args) 
    {
        int[] a = new int[]{1,4,1,2,7,5,2};
        countSort(a);
        for(int element:a)
            System.out.print(element+" ");
    }
}

輸出結果

1 1 2 2 4 5 7

 

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