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 - heap sort #1261

Merged
merged 5 commits into from
Apr 30, 2024
Merged
Changes from all commits
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/heap_sort.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
=begin
File: heap_sort.rb
Created Time: 2024-04-10
Author: junminhong ([email protected])
=end

### 堆的长度为 n ,从节点 i 开始,从顶至底堆化 ###
def sift_down(nums, n, i)
while true
# 判断节点 i, l, r 中值最大的节点,记为 ma
l = 2 * i + 1
r = 2 * i + 2
ma = i
ma = l if l < n && nums[l] > nums[ma]
ma = r if r < n && nums[r] > nums[ma]
# 若节点 i 最大或索引 l, r 越界,则无须继续堆化,跳出
break if ma == i
# 交换两节点
nums[i], nums[ma] = nums[ma], nums[i]
# 循环向下堆化
i = ma
end
end

### 堆排序 ###
def heap_sort(nums)
# 建堆操作:堆化除叶节点以外的其他所有节点
(nums.length / 2 - 1).downto(0) do |i|
sift_down(nums, nums.length, i)
end
# 从堆中提取最大元素,循环 n-1 轮
(nums.length - 1).downto(1) do |i|
# 交换根节点与最右叶节点(交换首元素与尾元素)
nums[0], nums[i] = nums[i], nums[0]
# 以根节点为起点,从顶至底进行堆化
sift_down(nums, i, 0)
end
end

### Driver Code ###
if __FILE__ == $0
nums = [4, 1, 3, 1, 5, 2]
heap_sort(nums)
puts "堆排序完成后 nums = #{nums.inspect}"
end