Heap Sort
code: python
from typing import List, Any
# O(nlogn), O(1)
def heap_sort(arr):
n = len(arr)
heap = Heap()
for v in arr:
heap.insert(v)
res = []
for _ in range(n):
res.append(heap.pop())
return res
class Heap:
def __init__(self):
def insert(self, value: Any) -> None:
self.heap.append(value)
self._up(len(self.heap) - 1)
def _up(self, index: int) -> None:
parent = (index - 1) // 2
self._up(parent)
def pop(self):
if not self.heap:
return None
if len(self.heap) > 1:
self.heap0 = self.heap.pop() self._down()
else:
self.heap.pop()
return min_value
def _down(self, index=0):
smallest = index
left_child = 2 * index + 1
right_child = 2 * index + 2
smallest = left_child
smallest = right_child
if smallest != index:
self._down(smallest)
def test_heap_sort():
assert heap_sort(5, 3, 4, 7, 2, 8, 6, 9, 1) == 1, 2, 3, 4, 5, 6, 7, 8, 9