方法1

/**
* 桶排序:C 语言
*
* @author skywang
* @date 2014/03/13
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 数组长度
#define LENGTH(array) ( (sizeof(array)) / (sizeof(array[0])) )

/*
* 桶排序
*
* 参数说明:
* a -- 待排序数组
* n -- 数组a的长度
* max -- 数组a中最大值的范围
*/
void bucket_sort(int a[], int n, int max)
{
int i, j;
int *buckets;

if (a==NULL || n<1 || max<1)
return ;

// 创建一个容量为max的数组buckets,并且将buckets中的所有数据都初始化为0。
if ((buckets=(int *)malloc(max*sizeof(int)))==NULL)
return ;
memset(buckets, 0, max*sizeof(int));

// 1. 计数
for(i = 0; i < n; i++)
buckets[a[i]]++;

// 2. 排序
for (i = 0, j = 0; i < max; i++)
while( (buckets[i]--) >0 )
a[j++] = i;

free(buckets);
}

void main()
{
int i;
int a[] = {8,2,3,4,3,6,6,3,9};
int ilen = LENGTH(a);

printf("before sort:");
for (i=0; i<ilen; i++)
printf("%d ", a[i]);
printf("\n");

bucket_sort(a, ilen, 10); // 桶排序

printf("after sort:");
for (i=0; i<ilen; i++)
printf("%d ", a[i]);
printf("\n");
}

方法2

// 桶排序
const bucketSort = (array, bucketSize) => {
if (array.length === 0) {
return array;
}

console.time('桶排序耗时');
let i = 0;
let minValue = array[0];
let maxValue = array[0];
for (i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i]; //输入数据的最小值
} else if (array[i] > maxValue) {
maxValue = array[i]; //输入数据的最大值
}
}

//桶的初始化
const DEFAULT_BUCKET_SIZE = 5; //设置桶的默认数量为 5
bucketSize = bucketSize || DEFAULT_BUCKET_SIZE;
const bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
const buckets = new Array(bucketCount);
for (i = 0; i < buckets.length; i++) {
buckets[i] = [];
}

//利用映射函数将数据分配到各个桶中
for (i = 0; i < array.length; i++) {
buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]);
}

array.length = 0;
for (i = 0; i < buckets.length; i++) {
quickSort(buckets[i]); //对每个桶进行排序,这里使用了快速排序
for (var j = 0; j < buckets[i].length; j++) {
array.push(buckets[i][j]);
}
}
console.timeEnd('桶排序耗时');

return array;
};

// 快速排序
const quickSort = (arr, left, right) => {
let len = arr.length,
partitionIndex;
left = typeof left != 'number' ? 0 : left;
right = typeof right != 'number' ? len - 1 : right;

if (left < right) {
partitionIndex = partition(arr, left, right);
quickSort(arr, left, partitionIndex - 1);
quickSort(arr, partitionIndex + 1, right);
}
return arr;
};

const partition = (arr, left, right) => {
//分区操作
let pivot = left, //设定基准值(pivot)
index = pivot + 1;
for (let i = index; i <= right; i++) {
if (arr[i] < arr[pivot]) {
swap(arr, i, index);
index++;
}
}
swap(arr, pivot, index - 1);
return index - 1;
};

const swap = (arr, i, j) => {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
};



const array = [4, 6, 8, 5, 9, 1, 2, 5, 3, 2];
console.log('原始array:', array);
const newArr = bucketSort(array);
console.log('newArr:', newArr);


/*
原始array: [
4, 6, 8, 5, 9,
1, 2, 5, 3, 2
]
桶排序耗时: 1.412ms
newArr: [
1, 2, 2, 3, 4,
5, 5, 6, 8, 9
]
*/

参考

     ​​桶排序 - 如果天空不死 -

​     JavaScript 数据结构与算法之美 - 桶排序、计数排序、基数排序 - 知乎​