桶排序的定義
先引用維基百科的一段話(huà)作為開(kāi)頭:
Bucket sort, or bin sort, is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
from Wikipedia Bucket sort
我的理解
顧名思義,我們先擺好幾個(gè)桶,這幾個(gè)桶呢是按順序放好的,例如:0, 1, 2, 3 .... , 10;現(xiàn)在,我們有一組數(shù): 3, 5, 2, 1, 6, 4, 2, 8, 9,我們?cè)趺唇o這組數(shù)去排序呢?首先尋找一個(gè)標(biāo)桿,就是桶 (因?yàn)橥暗捻樞虻恼_的)。
然后我們把 3 扔進(jìn)桶 3, 5 扔進(jìn)桶 5,一次類(lèi)推,然后在將這些桶的數(shù)一一打印出來(lái)就可以了。從小到大,從大到小任君選擇。
Code
這里寫(xiě)一下 C code,僅作參考:
#include <stdio.h>
int main(){
int a[11], i, j , t; // build 11 buckets
for (i = 0; i < 10; i++)
a[i] =0; // the initail values is zero
for (i = 1; i <= 5; i++){
// the example has 5 numbers so i is less than 5
scanf("%d", &t);
a[t]++;
}
for (i = 0; i <= 10; i++)
for(j = 1; j <= a[i]; j++)
printf("%d \n", i);
getchar();
return 0;
}
Reference:
https://en.wikipedia.org/wiki/Bucket_sort
《啊哈算法》 ISBN: 9787115354594