Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kim <3 <3 <3 #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
added functionality for heapsort with all tests passing
Kim Fasbender committed Sep 20, 2019
commit 21ded0c7499cb6e1e170503cb32986122d31a122
22 changes: 16 additions & 6 deletions lib/heap_sort.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
# This method uses a heap to sort an array.
# Time Complexity: O(n log n) - where n is the number of heap nodes in the list
# Space Complexity: O(1) - constant
def heapsort(list)
return list if list.empty? || list.length == 1

minHeap = MinHeap.new()

# This method uses a heap to sort an array.
# Time Complexity: ?
# Space Complexity: ?
def heap_sort(list)
raise NotImplementedError, "Method not implemented yet..."
end
until list.empty?
minHeap.add(list.pop)
end

until minHeap.empty?
list << minHeap.remove
end
Comment on lines +9 to +15

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very clear and elegant.


return list
end
9 changes: 8 additions & 1 deletion lib/min_heap.rb
Original file line number Diff line number Diff line change
@@ -81,7 +81,14 @@ def heap_down(index)

if @store[left_child_index].nil?
return
elsif @store[right_child_index].nil? || @store[left_child_index].key < @store[right_child_index].key
elsif @store[right_child_index].nil?
if @store[left_child_index].key < @store[index].key
swap(index, left_child_index)
end
return
end

if @store[left_child_index].key < @store[right_child_index].key
swap(index, left_child_index)
heap_down(left_child_index)
else
14 changes: 7 additions & 7 deletions test/heapsort_test.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
require_relative "test_helper"

xdescribe "heapsort" do
describe "heapsort" do
it "sorts an empty array" do
# Arrange
# Arrange
list = []

# Act
@@ -13,7 +13,7 @@
end

it "can sort a 1-element array" do
# Arrange
# Arrange
list = [5]

# Act
@@ -22,15 +22,15 @@
# Assert
expect(result).must_equal [5]
end

it "can sort a 5-element array" do
# Arrange
# Arrange
list = [5, 27, 3, 16, -50]

# Act
result = heapsort(list)

# Assert
expect(result).must_equal [-50, 3, 5, 16, 27]
end
end
end
end