diff --git a/lib/heap_sort.rb b/lib/heap_sort.rb index c8a32a4..ca6c499 100644 --- a/lib/heap_sort.rb +++ b/lib/heap_sort.rb @@ -1,5 +1,3 @@ - - # This method uses a heap to sort an array. # Time Complexity: ? # Space Complexity: ? diff --git a/lib/min_heap.rb b/lib/min_heap.rb index 6eaa630..11dbf90 100644 --- a/lib/min_heap.rb +++ b/lib/min_heap.rb @@ -1,6 +1,6 @@ class HeapNode attr_reader :key, :value - + # compare by key, priority field def initialize(key, value) @key = key @value = value @@ -17,7 +17,12 @@ def initialize # Time Complexity: ? # Space Complexity: ? def add(key, value = key) - raise NotImplementedError, "Method not implemented yet..." + new_node = HeapNode.new(key, value) + new_node_index = @store.length + @store.push(new_node) + heap_up(@store.length - 1) + + return new_node end # This method removes and returns an element from the heap @@ -25,8 +30,12 @@ def add(key, value = key) # Time Complexity: ? # Space Complexity: ? def remove() - raise NotImplementedError, "Method not implemented yet..." - end + removed = @store[0].value + swap(0, @store.length - 1) + @store.pop + heap_down(0) + return removed + end # Used for Testing @@ -52,20 +61,48 @@ def empty? private + def find_parent(index) + parent_index = (index - 1)/2 + return parent_index + end + # This helper method takes an index and # moves it up the heap, if it is less than it's parent node. # It could be **very** helpful for the add method. # Time complexity: ? # Space complexity: ? def heap_up(index) - + puts to_s + parent_index = find_parent(index) + if @store[parent_index].key <= @store[index].key || index == 0 + return + end + if @store[parent_index].key > @store[index].key + # puts @store[index].value + swap(parent_index, index) + index = parent_index + heap_up(index) + end end # This helper method takes an index and # moves it up the heap if it's smaller # than it's parent node. def heap_down(index) - raise NotImplementedError, "Method not implemented yet..." + puts 'heap down' + puts to_s + child_index = 2*index + 1 + if index >= @store.length - 1 || child_index >= @store.length - 1 + return + end + if @store[child_index].key >= @store[index].key + return + end + if @store[child_index].key < @store[index].key + swap(child_index, index) + index = child_index + heap_down(index) + end end # If you want a swap method... you're welcome