Last active
June 7, 2019 13:53
-
-
Save DanielAmah/cea9531627d1758e3111cbdd7f4f1cd7 to your computer and use it in GitHub Desktop.
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
# 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