Python Heap Sort
# Python3.x Python Heap Sort
[ Python3 Examples](#)
Heap sort is a sorting algorithm designed using the heap data structure. A heap is a nearly complete binary tree structure that also satisfies the heap property: the key value or index of a child node is always less than (or greater than) its parent node. Heap sort can be considered a selection sort that utilizes the concept of a heap for sorting.
!(#)
## Example
```python
def heapify(arr, n, i):
largest = i # Initialize largest as root
l = 2 * i + 1 # left = 2*i + 1
r = 2 * i + 2 # right = 2*i + 2
# See if left child of root exists and is greater than root
if l < n and arr < arr:
largest = l
# See if right child of root exists and is greater than the largest so far
if r < n and arr < arr:
largest = r
# Change root, if needed
if largest != i:
arr, arr = arr, arr # swap
# Heapify the root.
heapify(arr, n, largest)
# The main function to sort an array of given size
def heapSort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# One by one extract elements
for i in range(n-1, 0, -1):
arr, arr = arr, arr # swap
heapify(arr, i, 0)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
heapSort(arr)
n = len(arr)
print ("Sorted array is")
for i in range(n):
print ("%d" %arr),
The output of the above code is:
Sorted array is
5
6
7
11
12
13
[ Python3 Examples](#)
[](#)(#)
(#)[](#)
[Volcengine Coding Plan supports mainstream large models like Doubao, GLM, DeepSeek, Kimi, MiniMax, officially supplied, stable and reliable. Configuration Guide Β₯9.9/month Sign up now](https://maas.xfyun.cn/modelSquare?ch=maas_lm_l2E)
## 5 Notes Write a Note
1. #0 heuwst
674***591@qq.com [](#)13 Improved reference code:
1. Iterative heapify
2. Two iterative writing methods
```python
def heapify(arr):
n = len(arr)
for i in reversed(range(n // 2)):
shiftDown(arr, n, i)
def shiftDown(arr, n, k):
while 2 * k + 1 < n:
j = 2 * k + 1
if j + 1 < n and arr[j + 1] < arr:
j += 1
if arr <= arr:
break
arr, arr = arr, arr
k = j
def shiftDown2(arr, n, k):
smallest, l, r = k, 2 * k + 1, 2 * k + 2
while l < n:
if arr < arr:
smallest = l
if r < n and arr < arr:
smallest = r
if smallest == k:
break
arr, arr = arr, arr
k, smallest = smallest, k
l, r = 2 * k + 1, 2 * k + 2
YouTip