function bucketSort($arr) {
// 找到最大值和最小值
$minValue = min($arr);
$maxValue = max($arr);
// 计算桶的数量
$bucketCount = floor(($maxValue - $minValue) / count($arr)) + 1;
// 创建桶
$buckets = array();
for ($i = 0; $i < $bucketCount; $i++) {
$buckets[$i] = array();
}
// 将元素放入桶中
foreach ($arr as $value) {
$bucketIndex = floor(($value - $minValue) / count($arr));
$buckets[$bucketIndex][] = $value;
}
// 对每个桶进行排序
$sortedArray = array();
foreach ($buckets as $bucket) {
sort($bucket);
$sortedArray = array_merge($sortedArray, $bucket);
}
return $sortedArray;
}
// 示例用法
$unsortedArray = array(5, 9, 2, 6, 1, 8, 3, 7);
$sortedArray = bucketSort($unsortedArray);
echo "Sorted Array: ";
foreach ($sortedArray as $element) {
echo $element . " ";
}