Ruby 堆排序

boshrc · 2014年08月06日 · 最后由 torvaldsdb 回复于 2016年12月12日 · 1987 次阅读
class Allsorts
  def self.build_max_root_heap(arr)
    # build the arr to a heap with max root 
    return arr if arr.size <=1
    (1..(Math.log(arr.size,2).to_i)).to_a.reverse.each do |i|
      end_ ||= arr.size-1
      ((2**i-1)..end_).each do |j|
        if j % 2 == 0
          arr[j-1], arr[j] = arr[j], arr[j-1] if arr[j-1] < arr[j]
          arr[j/2-1], arr[j-1] = arr[j-1], arr[j/2-1] if arr[j/2-1]<arr[j-1]
        end
        if j == end_ and j % 2 !=0 
          arr[j/2], arr[j] = arr[j], arr[j/2] if arr[j/2] < arr[j]
        end
      end
    end
    arr
  end

  def self.heapsort(arr)
    return arr if arr.size <=1
    (arr.size - 1).times do |i|
      j = arr.size - i - 1
      arr[0..j] = self.build_max_root_heap(arr[0..j])
      arr[j], arr[0] = arr[0], arr[j]
    end
    arr
  end
end

这个要表达什么

需要 登录 后方可回复, 如果你还没有账号请 注册新账号