Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

桶排序 #199

Open
Sunny-117 opened this issue Nov 3, 2022 · 1 comment
Open

桶排序 #199

Sunny-117 opened this issue Nov 3, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@bljessica
Copy link

bljessica commented Nov 30, 2023

const bucketSort = (arr) => {
  const max = Math.max(...arr)
  const min = Math.min(...arr)
  const len = arr.length
  const bucketNum = Math.floor((max - min) / len) + 1
  const buckets = new Array(bucketNum).fill(0).map(() => [])
  // 收集到桶中
  for (const num of arr) {
    buckets[Math.floor((num - min) / len)].push(num)
  }
  // 各个桶中各自排序
  for (const bucket of buckets) {
    bucket.sort((a, b) => a - b) // 一般用插入排序或快速排序
  }
  // 整合回原数组
  let k = 0
  for (let i = 0; i < buckets.length; i++) {
    for (let j = 0; j < buckets[i].length; j++) {
      arr[k++] = buckets[i][j]
    }
  }
  return arr
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants