Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created December 27, 2022 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZhouYang1993/874d0b023956820dab06e745b587bf8f to your computer and use it in GitHub Desktop.
Save ZhouYang1993/874d0b023956820dab06e745b587bf8f to your computer and use it in GitHub Desktop.
A Deep Dive into Heap and Heap Sort in Python: From Beginner to Expert
def heap_sort(arr):
# Build a max heap from the input list
heapify(arr)
# Extract the root element (the maximum value) and place it at the end of the sorted list
sorted_arr = []
while arr:
sorted_arr.append(heappop(arr))
# Return the sorted list
return sorted_arr
def heapify(arr):
# Start from the last non-leaf node and heapify all nodes from bottom to top
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify_node(arr, i, n)
def heapify_node(arr, i, n):
# Heapify the node at index i and its children
left = 2 * i + 1
right = 2 * i + 2
largest = i
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify_node(arr, largest, n)
def heappop(arr):
# Extract the root element (the maximum value) from the heap
root = arr[0]
arr[0] = arr[-1]
del arr[-1]
heapify(arr)
return root
print(heap_sort([5, 2, 7, 2077, 3, 99, 4, 54, 20]))
# [2077, 99, 54, 20, 7, 5, 4, 3, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment