heap sort by ruby

代码

#heap_sort.rb

def max_heap? array

  (array.size-1).downto(1) do |i|
    parent = (i-1)/2
    return false if array[parent] < array[i]
  end
  true
end

def max_heap_unshift_down array, tail
  i = tail
  while i > 0
    parent = (i-1)/2
    if  array[parent] < array[i]
       array[i], array[parent] = array[parent], array[i]
       i = parent
    else
      break
    end
  end
end

def max_heap_shift_up array, tail
  array[0], array[tail] = array[tail], array[0]
  tail = tail-1
  i = 0;
  while true
    next_i = i
    left_child = 2*i+1
    right_child = 2*i+2
    if right_child <=tail and array[left_child] < array[right_child]
      next_i = right_child
    elsif left_child <=tail
      next_i = left_child
    end

    if i < next_i and array[i] < array[next_i]
      array[i], array[next_i] = array[next_i], array[i]
      i = next_i
    else
      break
    end
  end
end

def heap_sort array
  last = array.size-1
  1.upto(last) do |tail|
    max_heap_unshift_down array, tail
  end
 
  last.downto(0) do |tail|
    max_heap_shift_up array, tail
  end
  array

end

 

测试

#heap_sort_spec.rb

require 'heap_sort'

describe "heap_sort" do
  it "should max_heap? [5, 4, 3, 2,1]" do
    a = [5, 4, 3, 2, 1]
    max_heap?(a).should == true
  end
 
  it "should heap_shift_up [5,4,3,2,1]" do
    a = [5,4,3,2,1]
    max_heap_shift_up a, a.size-1
    max_heap?(a[0, a.size-1]).should== true
  end
 
  it "should heap_unshift_down [4,3,2,1,5]" do
    a = [4,3,2,1,5]
    max_heap_unshift_down a,a.size-1
    max_heap?(a).should== true
  end

  it "should sort [1002,43, 12, 46]" do
    a=[1002,43, 12, 46]
    b = heap_sort a
    b.should== [12, 43, 46, 1002]
  end

  it "should sort [6,5,4,3,2,1]" do
    a=[6,5,4,3,2,1]
    b = heap_sort a
    b.should== [1,2,3,4,5,6]
  end
end

 

posted @ 2010-05-30 00:45  napoleon_liu  阅读(359)  评论(0编辑  收藏  举报