Commit 94c96ee

mo khan <mo@mokhan.ca>
2013-10-13 03:33:19
switch MinHeap to Heap and adjust so that it can be used as both a min or max heap.
1 parent f199bfd
Changed files (5)
lib/data_structures/heap.rb
@@ -0,0 +1,27 @@
+class Heap
+  def initialize(items = [], sorting = QuickSort.new)
+    @items = sorting.sort(items)
+    @sort_strategy = sorting
+  end
+
+  def insert(item)
+    @items.push(item)
+    @items = @sort_strategy.sort(@items)
+  end
+
+  def min
+    @items.shift
+  end
+
+  def max
+    @items.pop
+  end
+
+  def empty?
+    @items.empty?
+  end
+
+  def self.heapify(items)
+    Heap.new(items)
+  end
+end
lib/data_structures/min_heap.rb
@@ -1,14 +0,0 @@
-class MinHeap
-  def initialize(items = [])
-    @items = items
-    @items.sort!
-  end
-
-  def min
-    @items.shift
-  end
-
-  def empty?
-    @items.empty?
-  end
-end
spec/data_structures/heap_spec.rb
@@ -0,0 +1,42 @@
+require "spec_helper"
+
+describe Heap do
+  context :min do
+    context "emtpy" do
+      it "should return nil" do
+        heap = Heap.new
+        heap.min.should be_nil
+        heap.empty?.should be_true
+      end
+    end
+
+    context "full" do
+      it "should return the items order from lowest to highest" do
+        n = 10
+        numbers = Array.new(n) { rand(n) }
+        heap = Heap.heapify(numbers.dup)
+
+        results = []
+        results << heap.min until heap.empty?
+        results.should == numbers.sort
+      end
+    end
+  end
+
+  context :max do
+    it "should return nil when empty" do
+      heap = Heap.new
+      heap.max.should be_nil
+      heap.empty?.should be_true
+    end
+
+    it "should return the items in order from highest to lowest" do
+      n = 10
+      numbers = Array.new(n) { rand(n) }
+      heap = Heap.heapify(numbers.dup)
+      results = []
+      results.push(heap.max) until heap.empty?
+      results.should == numbers.sort.reverse
+    end
+  end
+end
spec/data_structures/min_heap_spec.rb
@@ -1,18 +0,0 @@
-require "spec_helper"
-
-describe MinHeap do
-  it "should return nil" do
-    heap = MinHeap.new
-    heap.min.should be_nil
-  end
-
-  it "should return the items order from lowest to highest" do
-    n = 100
-    numbers = Array.new(n) { rand(n) }
-    heap = MinHeap.new(numbers.dup)
-
-    results = []
-    results << heap.min until heap.empty?
-    results.should == numbers.sort
-  end
-end
spec/spec_helper.rb
@@ -11,4 +11,4 @@ require_relative '../lib/data_structures/dynamic_array_stack'
 require_relative '../lib/data_structures/binary_tree'
 require_relative '../lib/data_structures/avl_tree'
 require_relative '../lib/data_structures/hash_table'
-require_relative '../lib/data_structures/min_heap'
+require_relative '../lib/data_structures/heap'