示例代码纯粹是为了加深印象,选择的目标语言有更便捷的实现方式,另外去掉了一些假设条件检查。
#encoding:gbk
Size = 20
class Array
attr_accessor :heap_size
end
arr = Array.new(Size) do #初始化待排序数组,随机填写元素
rand(Size)
end
def left(i)
2*i
end
def right(i)
2*i + 1
end
def parent(i)
i/2
end
def max_heapify(a,i)
l,r,largest = left(i),right(i),0
if l <= a.heap_size - 1 and a[l] > a[i]
largest = l
else
largest = i
end
if r <= a.heap_size - 1 and a[r] > a[largest]
largest = r
end
if largest != i
a[i],a[largest] = a[largest],a[i]
max_heapify(a,largest)
end
end
def build_max_heap(a)
a.heap_size = a.size
(a.size/2 - 1).downto 0 do |i|
max_heapify(a,i)
end
end
def heap_sort(a)
build_max_heap(a)
(a.size - 1).downto 1 do |i|
a[0],a[i] = a[i],a[0]
a.heap_size -= 1
max_heapify(a,0)
end
end
puts arr.inspect
arrc = arr.clone
heap_sort(arrc)
puts arrc.inspect
输出如下:
---------- Ruby ----------
[10, 5, 10, 7, 17, 8, 6, 0, 0, 14, 8, 5, 1, 1, 5, 5, 10, 17, 1, 0]
[0, 0, 0, 1, 1, 1, 5, 5, 5, 5, 6, 7, 8, 8, 10, 10, 10, 14, 17, 17]
Output completed (0 sec consumed) - Normal Termination
这个排序算法代码比较紧凑,排序的想法有些取巧,好比用簸箕筛选农作物的种子呢,理解起来是需要花些时间的。