MCPcopy Create free account
hub / github.com/geekcomputers/Python / heapify

Function heapify

Sorting Algorithms/heap_sort.py:1–20  ·  view source on GitHub ↗
(nums, heap_size, root_index)

Source from the content-addressed store, hash-verified

1def heapify(nums, heap_size, root_index):
2 # Assume the index of the largest element is the root index
3 largest = root_index
4 left_child = (2 * root_index) + 1
5 right_child = (2 * root_index) + 2
6
7 # If the left child of the root is a valid index, and the element is greater
8 # than the current largest element, then update the largest element
9 if left_child < heap_size and nums[left_child] > nums[largest]:
10 largest = left_child
11
12 # Do the same for the right child of the root
13 if right_child < heap_size and nums[right_child] > nums[largest]:
14 largest = right_child
15
16 # If the largest element is no longer the root element, swap them
17 if largest != root_index:
18 nums[root_index], nums[largest] = nums[largest], nums[root_index]
19 # Heapify the new root element to ensure it's the largest
20 heapify(nums, heap_size, largest)
21
22
23def heap_sort(nums):

Callers 1

heap_sortFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected