Conversation
CheezItMan
left a comment
There was a problem hiding this comment.
It passes all the tests, but it doesn't do what it's supposed to do. Take a look at my comments and let me know what questions you have.
There is some good code here, but a lot is just... rough, maybe make a 2nd stab at this.
| def heap_sort(list) | ||
| raise NotImplementedError, "Method not implemented yet..." | ||
| end No newline at end of file | ||
| def heapsort(list) |
There was a problem hiding this comment.
Also you add things into a heap, but in the internal structure the items are not sorted. They're maintained in heap order with the parent smaller than it's children. You have to REMOVE elements from the heap 1-by-1 to be guaranteed to get it into order.
| # Time Complexity: O(logn) | ||
| # Space Complexity: O(1) | ||
| def add(key, value = key) |
lib/min_heap.rb
Outdated
| if @store.empty? | ||
| @store << HeapNode.new(key, value) |
lib/min_heap.rb
Outdated
| # Space Complexity: O(1) | ||
| def remove() | ||
| raise NotImplementedError, "Method not implemented yet..." | ||
| min = @store.min_by {|node| node.key} |
There was a problem hiding this comment.
This is a linear search, you're totally losing the advantage of a Heap here!
| # Time complexity: O(0) | ||
| # Space complexity: O(0) | ||
| def empty? |
| # Time complexity: O(logn) | ||
| # Space complexity: O(0) | ||
| def heap_up(index) |
| # 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) |
There was a problem hiding this comment.
This isn't working because you've got to:
- Check the both left and right child
- And swap with the smaller of the two, if needed
- Consider the case where there is a left child and not a right child
| swap(index, index * 2 + 1) | ||
| swap(index, index * 2 + 2) if @store[index * 2 + 2] != nil && @store[index].key > @store[index * 2 + 2].key |
Heaps Practice
Congratulations! You're submitting your assignment!
Comprehension Questions
heap_up&heap_downmethods useful? Why?