Skip to content

Commit a44fc9a

Browse files
committed
Added a heap sort based on MaxHeap
1 parent 98bf700 commit a44fc9a

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

chap09_heaps/heapsort_maxheap.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Ref: https://github.com/keon/algorithms/blob/master/algorithms/sort/heap_sort.py
2+
3+
4+
def heap_sort(arr, simulation=False):
5+
"""Heap sort that uses a max heap to sort an array in ascending order.
6+
"""
7+
iteration = 0
8+
if simulation is True:
9+
print(f"Iteration {iteration}:", *arr)
10+
11+
for idx in range(len(arr) - 1, 0, -1):
12+
iteration = _heapify(arr, idx, simulation, iteration)
13+
14+
if simulation:
15+
iteration += 1
16+
print(f"Iteration {iteration}:", *arr)
17+
18+
return arr
19+
20+
21+
def _heapify(arr, end, simulation, iteration):
22+
last_parent = (end - 1) // 2
23+
24+
# Iterate from last parent to first
25+
for parent in range(last_parent, -1, -1):
26+
current_parent = parent
27+
28+
while current_parent <= last_parent:
29+
child = current_parent * 2 + 1
30+
31+
if child + 1 <= end and arr[child] < arr[child + 1]:
32+
child += 1
33+
34+
if arr[child] > arr[current_parent]:
35+
arr[current_parent], arr[child] = (
36+
arr[child],
37+
arr[current_parent],
38+
)
39+
current_parent = child
40+
41+
if simulation is True:
42+
iteration += 1
43+
print(f"Iteration {iteration}:", *arr)
44+
else:
45+
break
46+
47+
arr[0], arr[end] = arr[end], arr[0]
48+
return iteration
49+
50+
51+
def main() -> None:
52+
arr = [9, 1, 3]
53+
54+
assert heap_sort(arr) == [1, 3, 9]
55+
assert heap_sort(arr, simulation=True) is not None
56+
57+
58+
if "__main__" == __name__:
59+
main()

0 commit comments

Comments
 (0)