桶排序的定义
先引用维基百科的一段话作为开头:
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
我的理解
顾名思义,我们先摆好几个桶,这几个桶呢是按顺序放好的,例如:0, 1, 2, 3 …. , 10;现在,我们有一组数: 3, 5, 2, 1, 6, 4, 2, 8, 9,我们怎么给这组数去排序呢?首先寻找一个标杆,就是桶 (因为桶的顺序的正确的)。
然后我们把 3 扔进桶 3, 5 扔进桶 5,一次类推,然后在将这些桶的数一一打印出来就可以了。从小到大,从大到小任君选择。
Code
这里写一下 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