Skip to content

Instantly share code, notes, and snippets.

@DanielAmah
Last active June 7, 2019 13:53
Show Gist options
  • Save DanielAmah/cea9531627d1758e3111cbdd7f4f1cd7 to your computer and use it in GitHub Desktop.
Save DanielAmah/cea9531627d1758e3111cbdd7f4f1cd7 to your computer and use it in GitHub Desktop.
# Heap Sorting Algorithm
# the root node of the heap is always the largest value
# build a sorted array by repeatedly removing the root node
# push to our new array
# heapify the max heap so that the new, largest value node is at the root.
def heap_sort(array)
n = array.length - 1
a = array
# build a max heap
(n / 2).downto(0) do |i|
heapify(a, i, n)
end
# when array length is greater than 1
# swap root element with the last element
# reduce the length by 1
# re-build the heap so that it satisfies the max-heap condition
while n > 0
a[0], a[n] = a[n], a[0]
n -= 1
heapify(a, 0, n)
end
a
end
# sift the elements until they are in their rightful place
# parent indicates where to start sifting, limit indicates how far down the heap to sift
def heapify(array, parent, limit)
root = array[parent]
while (child = 2 * parent) <= limit do
child += 1 if child < limit && array[child] < array[child + 1]
break if root >= array[child]
array[parent], parent = array[child], child
end
array[parent] = root
end
p heap_sort([2,1,5,7,8,3,0,4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment