Skip to content

Instantly share code, notes, and snippets.

@CelesteComet
Last active March 1, 2018 18:14
Show Gist options
  • Save CelesteComet/f5d1aafa0e0ee0af96c8ca4bf05012bb to your computer and use it in GitHub Desktop.
Save CelesteComet/f5d1aafa0e0ee0af96c8ca4bf05012bb to your computer and use it in GitHub Desktop.
heap sort
require_relative "heap"
class Array
def heap_sort!
# Create a heap
heap = BinaryMinHeap.new
# make an array to keep the sorted elements
sorted = []
# push all the array's elements into the heap
self.each do |e|
heap.push(e)
end
# take out the smallest element out of the heap
smallest = heap.extract
# while we have elements in the heap, push the smallest into the sorted array
while smallest
sorted.push(smallest)
smallest = heap.extract
end
# Now the sorted array has all the elements sorted but the self array does not...
# copy each of the elements in the sorted array to the self array
sorted.each_with_index do |element, idx|
self[idx] = element
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment