Last active
March 1, 2018 18:14
-
-
Save CelesteComet/f5d1aafa0e0ee0af96c8ca4bf05012bb to your computer and use it in GitHub Desktop.
heap sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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