Last active
April 26, 2021 13:27
-
-
Save harbirchahal/b2170fb8b4923e1722652fe6100567e0 to your computer and use it in GitHub Desktop.
Algo: Heap -> Heapify
This file contains hidden or 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
def heapify(array): | |
last_index = len(array) - 1 | |
for index in range(last_index, -1, -1): | |
bubble_down(array, index) | |
def bubble_down(array, index): | |
index_limit = len(array) - 1 | |
lchild_index = (index + 1) * 2 - 1 | |
rchild_index = lchild_index + 1 | |
left_child = array[lchild_index] if (lchild_index <= index_limit) else 0 | |
right_child = array[rchild_index] if (rchild_index <= index_limit) else 0 | |
if (array[index] < left_child or array[index] < right_child): | |
max_child_index = lchild_index if left_child > right_child else rchild_index | |
array[index], array[max_child_index] = array[max_child_index], array[index] | |
bubble_down(array, max_child_index) | |
# Main | |
heapify([10, 20, 15, 12, 40, 25, 18]) | |
# Before: | |
# [10, 20, 15, 12, 40, 25, 18] | |
# | |
# 10 | |
# 20 15 | |
# 12 40 25 18 | |
# After: | |
# [40, 20, 25, 12, 10, 15, 18] | |
# | |
# 40 | |
# 20 25 | |
# 12 10 15 18 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ref: Abdul Bari - Heapify