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

feat: add ruby code block - bucket sort #1285

Merged
merged 4 commits into from
Apr 30, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions codes/ruby/chapter_sorting/bucket_sort.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
=begin
File: bucket_sort.rb
Created Time: 2024-04-17
Author: Martin Xu ([email protected])
=end

### 桶排序 ###
def bucket_sort(nums)
# 初始化 k = n/2 个桶,预期向每个桶分配 2 个元素
k = nums.length / 2
buckets = []
0.upto(k - 1) do |i|
buckets << []
end
martinx marked this conversation as resolved.
Show resolved Hide resolved

# 1. 将数组元素分配到各个桶中
nums.each do |num|
# 输入数据范围为 [0, 1),使用 num * k 映射到索引范围 [0, k-1]
i = (num * k).to_i
# 将 num 添加进桶 i
buckets[i] << num
end

# 2. 对各个桶执行排序
buckets.each do |bucket|
# 使用内置排序函数,也可以替换成其他排序算法
bucket.sort!
end

# 3. 遍历桶合并结果
i = 0
buckets.each do |bucket|
bucket.each do |num|
nums[i] = num
i += 1
end
end
end

# 测试代码
krahets marked this conversation as resolved.
Show resolved Hide resolved
if __FILE__ == $0
nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37]
martinx marked this conversation as resolved.
Show resolved Hide resolved
bucket_sort(nums)
puts "桶排序完成后 nums = #{nums}"
end