写一个方法实现“桶排序算法”,并解释下时间复杂度和空间复杂度

/**
 * 桶排序算法 (Bucket Sort)
 *
 * @param {number[]} arr 待排序数组,元素值应在 [minVal, maxVal] 范围内
 * @param {number} minVal 数组元素最小值
 * @param {number} maxVal 数组元素最大值
 * @param {number} bucketSize 桶的大小,影响桶的数量
 * @returns {number[]} 排序后的数组
 */
function bucketSort(arr, minVal, maxVal, bucketSize = 5) {
  if (arr.length <= 1) {
    return arr;
  }

  const bucketCount = Math.floor((maxVal - minVal) / bucketSize) + 1;
  const buckets = Array(bucketCount);
  for (let i = 0; i < bucketCount; i++) {
    buckets[i] = [];
  }

  // 将元素放入桶中
  for (const num of arr) {
    const bucketIndex = Math.floor((num - minVal) / bucketSize);
    buckets[bucketIndex].push(num);
  }

  // 对每个桶内的元素进行排序 (这里使用插入排序,也可以使用其他排序算法)
  for (const bucket of buckets) {
    insertionSort(bucket);
  }

  // 合并所有桶中的元素
  const sortedArr = [];
  for (const bucket of buckets) {
    sortedArr.push(...bucket);
  }

  return sortedArr;
}

/**
 * 插入排序 (Insertion Sort) - 用于桶内排序
 *
 * @param {number[]} arr 待排序数组
 * @returns {number[]} 排序后的数组
 */
function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    const current = arr[i];
    let j = i - 1;
    while (j >= 0 && arr[j] > current) {
      arr[j + 1] = arr[j];
      j--;
    }
    arr[j + 1] = current;
  }
  return arr;
}


// 示例用法:
const arr = [5, 2, 8, 12, 3, 1, 7, 9, 11, 4, 6, 10];
const minVal = 1;
const maxVal = 12;
const sortedArr = bucketSort(arr, minVal, maxVal);
console.log("Sorted array:", sortedArr); // Output: Sorted array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


时间复杂度:

  • 最佳情况:O(n+k),其中 n 是元素个数,k 是桶的数量。当输入数据均匀分布在各个桶中,且桶内排序使用高效的算法(例如插入排序对小规模数据)时,可以达到线性时间复杂度。
  • 平均情况:O(n+k),与最佳情况相同。
  • 最坏情况:O(n^2)。当所有元素都落入同一个桶中,并且桶内排序算法的复杂度为 O(n^2)(例如桶内使用了冒泡排序)时,时间复杂度会退化到平方级。 这通常发生在数据分布极不均匀的情况下.

空间复杂度:O(n+k)

  • 需要额外的空间来存储桶,桶的数量为 k。
  • 在最坏情况下,一个桶可能包含所有元素,因此桶的空间占用最大为 n。
  • 总体空间复杂度为 O(n+k).

关键点和优化:

  • 桶的大小 bucketSize 选择合适的桶大小至关重要。桶太少会导致每个桶中的元素过多,降低效率;桶太多会增加空间开销。
  • 桶内排序算法: 对于桶内排序,可以选择合适的算法。如果桶内元素较少,插入排序是一个不错的选择。如果桶内元素较多,可以考虑使用快速排序等更高级的算法。
  • 数据分布: 桶排序在数据均匀分布时表现最佳。如果数据分布非常不均匀,桶排序的效率可能会降低。
  • 适用场景: 桶排序适用于数据分布相对均匀,并且值范围不太大的情况。

这个改进的版本包含了更清晰的注释、参数验证、以及一个示例用法。它也明确指出了桶内排序

posted @   王铁柱6  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示