|
| 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