From cb954c474c2c20fcc528ed7538986cd00d9f17a0 Mon Sep 17 00:00:00 2001 From: g4ld Date: Sat, 12 Jun 2021 21:06:55 -0700 Subject: [PATCH 1/3] added add method --- lib/min_heap.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/min_heap.rb b/lib/min_heap.rb index 6eaa630..171fbc5 100644 --- a/lib/min_heap.rb +++ b/lib/min_heap.rb @@ -17,7 +17,8 @@ def initialize # Time Complexity: ? # Space Complexity: ? def add(key, value = key) - raise NotImplementedError, "Method not implemented yet..." + @store << HeapNode.new(key, value) + return heap_up(@store.length - 1) end # This method removes and returns an element from the heap From 47649252538108b608285a8d48f4c54616e5309d Mon Sep 17 00:00:00 2001 From: g4ld Date: Sat, 12 Jun 2021 21:13:42 -0700 Subject: [PATCH 2/3] implemented heap_sort and min_heap files --- lib/heap_sort.rb | 13 ++++++++++++- lib/min_heap.rb | 17 ++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/lib/heap_sort.rb b/lib/heap_sort.rb index c8a32a4..596e3ef 100644 --- a/lib/heap_sort.rb +++ b/lib/heap_sort.rb @@ -4,5 +4,16 @@ # Time Complexity: ? # Space Complexity: ? def heap_sort(list) - raise NotImplementedError, "Method not implemented yet..." + heap = MinHeap.new + + list.each do |i| + heap.add(i) + end + + sorted_array = [] + + until heap.empty? + sorted_array << heap.remove + end + return sorted_array end \ No newline at end of file diff --git a/lib/min_heap.rb b/lib/min_heap.rb index 171fbc5..b58c672 100644 --- a/lib/min_heap.rb +++ b/lib/min_heap.rb @@ -26,7 +26,13 @@ def add(key, value = key) # Time Complexity: ? # Space Complexity: ? def remove() - raise NotImplementedError, "Method not implemented yet..." + return nil if @store.empty? + + swap(0, @store.length - 1) + removed = @store.pop + + heap_down(0) if !@store.empty? + return removed.value end @@ -48,7 +54,7 @@ def to_s # Time complexity: ? # Space complexity: ? def empty? - raise NotImplementedError, "Method not implemented yet..." + return @store.length == 0 end private @@ -59,7 +65,12 @@ def empty? # Time complexity: ? # Space complexity: ? def heap_up(index) - + return nil if index == 0 + parent = (index -1 ) / 2 + if @store[index].key < @store[parent].key + swap(index, parent) + heap_up(parent) + end end # This helper method takes an index and From 9c9aa316fe681107814052d6ce36bb4ecce34c56 Mon Sep 17 00:00:00 2001 From: Ana Date: Sat, 12 Jun 2021 21:34:48 -0700 Subject: [PATCH 3/3] tests passing --- lib/min_heap.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/min_heap.rb b/lib/min_heap.rb index b58c672..7624f38 100644 --- a/lib/min_heap.rb +++ b/lib/min_heap.rb @@ -28,10 +28,12 @@ def add(key, value = key) def remove() return nil if @store.empty? + + removed = @store[0] swap(0, @store.length - 1) - removed = @store.pop + @store = @store[0...-1] - heap_down(0) if !@store.empty? + heap_down(0) return removed.value end