Created
July 13, 2019 11:55
-
-
Save pdkproitf/ef94f2707426ccd27336504a6692bc52 to your computer and use it in GitHub Desktop.
Implement heap sort in ruby
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
# Algorithms: https://www.geeksforgeeks.org/heap-sort/ | |
module MaxHeapSort | |
extend self | |
@heap = Array.new | |
@sorted = Array.new | |
def create_heap(arr) | |
arr.each_with_index { |num, index| insert(index, num) } | |
@heap | |
end | |
def insert(index, node) | |
@heap[index] = node | |
bubble_up(index) | |
end | |
def bubble_up(index) | |
parent_index = (index - 1) / 2 | |
child_index = index | |
return if child_index.zero? | |
if @heap[child_index] > @heap[parent_index] | |
swap(parent_index, child_index) | |
bubble_up(parent_index) | |
end | |
end | |
def swap(parent_index, child_index) | |
@heap[child_index], @heap[parent_index] = @heap[parent_index], @heap[child_index] | |
end | |
def extract_min | |
while @heap.length > 0 | |
@sorted << @heap.first | |
swap(0, @heap.length - 1) | |
@heap.delete_at(@heap.length - 1) | |
sink_down(0) | |
end | |
@sorted | |
end | |
def sink_down(parent_index) | |
biggest_index = parent_index | |
left_child = 2 * parent_index + 1 | |
right_child = 2 * parent_index + 2 | |
biggest_index = left_child if @heap[left_child] && @heap[left_child] > @heap[biggest_index] | |
biggest_index = right_child if @heap[right_child] && @heap[right_child] > @heap[biggest_index] | |
return if biggest_index == parent_index | |
swap(parent_index, biggest_index) | |
sink_down(biggest_index) | |
end | |
def sort(arr) | |
puts '------------------------------MAX HEAP SORT O(nlogn)--------------------------' | |
print create_heap(arr) | |
puts '' | |
print extract_min | |
puts '' | |
end | |
end | |
MaxHeapSort.sort([3,7,8,4,10,16,2,1,12]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment