Skip to content
Browse files

a simple heap implementation

  • Loading branch information...
1 parent 389bdf0 commit a282bd9bdab68edff643be22e844305cdfc1bb7e @look committed
Showing with 131 additions and 0 deletions.
  1. +85 −0 lib/heap.rb
  2. +46 −0 tests/heap_test.rb
View
85 lib/heap.rb
@@ -0,0 +1,85 @@
+module CSBS
+ class Heap
+ @array = []
+
+ def initialize(array=nil)
+ if array
+ @array = array
+ end
+ end
+
+ def array
+ @array
+ end
+
+ def length
+ array.length
+ end
+
+ def self.parent(i)
+ return (i-1)/2
+ end
+
+ def self.left(i)
+ return (2 * i) + 1
+ end
+
+ def self.right(i)
+ return (2 * i) + 2
+ end
+
+ def self.build_heap(array)
+ heap = Heap.new(array)
+
+
+ ((array.length-1)/2).downto(0) do |i|
+ heap.heapify(i)
+ end
+
+ heap
+ end
+
+ def heapify(i)
+ left = Heap.left(i)
+ right = Heap.right(i)
+
+ if left <= (array.length - 1) && array[left] > array[i]
+ largest = left
+ else
+ largest = i
+ end
+
+ if right <= (array.length - 1) && array[right] > array[largest]
+ largest = right
+ end
+
+ if largest != i
+ array[i], array[largest] = array[largest], array[i]
+ heapify(largest)
+ end
+ end
+
+ def max
+ array.first
+ end
+
+ def extract_max
+ if array.empty?
+ raise "Heap underflow"
+ end
+
+ max = array.shift
+ heapify(0)
+ max
+ end
+
+ def insert(key)
+ i = array.length
+ while i > 0 && array[Heap.parent(i)] < key
+ array[i] = array[Heap.parent(i)]
+ i = Heap.parent(i)
+ end
+ array[i] = key
+ end
+ end
+end
View
46 tests/heap_test.rb
@@ -0,0 +1,46 @@
+require 'heap'
+require 'test/unit'
+
+class HeapTest < Test::Unit::TestCase
+ include CSBS
+
+ def test_heapify
+ heap = Heap.new([16, 4, 10, 14, 7, 9, 3, 2, 8, 1])
+
+ heap.heapify(1)
+
+ assert_equal([16, 14, 10, 8, 7, 9, 3, 2, 4, 1], heap.array)
+ end
+
+ def test_build_heap
+ heap = Heap.build_heap([1, 2, 3, 4, 5, 6, 7, 8])
+
+ assert_equal([8, 5, 7, 4, 1, 6, 3, 2], heap.array)
+ end
+
+ def test_max
+ heap = Heap.build_heap([10, 11, 3])
+ assert_equal(11, heap.max)
+ end
+
+ def test_extract_max
+ heap = Heap.build_heap([1, 2, 3, 4, 5, 6, 7, 8])
+ max = heap.extract_max
+ assert_equal(8, max)
+ assert_equal([7, 6, 4, 1, 5, 3, 2], heap.array)
+ end
+
+ def test_extract_max_on_empty_heap
+ heap = Heap.new([])
+ assert_raise RuntimeError do
+ max = heap.extract_max
+ end
+ end
+
+ def test_insert
+ heap = Heap.build_heap([16, 14, 10, 8, 7, 9, 3, 2, 4, 1])
+ heap.insert(15)
+ assert_equal([16, 15, 10, 8, 14, 9, 3, 2, 4, 1, 7], heap.array)
+ end
+end
+

0 comments on commit a282bd9

Please sign in to comment.
Something went wrong with that request. Please try again.