|
| 1 | +# -*- coding: UTF-8 -*- |
| 2 | +# |
| 3 | +# Heap Sort Algorithm |
| 4 | +# The All ▲lgorithms library for python |
| 5 | +# |
| 6 | +# Contributed by: DatHydroGuy |
| 7 | +# Github: @DatHydroGuy |
| 8 | +# |
| 9 | + |
| 10 | + |
| 11 | +def build_heap(array_to_sort, array_length, index): |
| 12 | + """ |
| 13 | + Build a heap, where each node has two child nodes, and a root node is greater than both child nodes. |
| 14 | + """ |
| 15 | + largest = index # Flag the largest element as the last (root) element |
| 16 | + left = 2 * index + 1 # Calculate index of left child node |
| 17 | + right = 2 * index + 2 # Calculate index of right child node |
| 18 | + |
| 19 | + # See if left child of root exists and is greater than root |
| 20 | + if left < array_length and array_to_sort[index] < array_to_sort[left]: |
| 21 | + largest = left |
| 22 | + |
| 23 | + # See if right child of root exists and is greater than root |
| 24 | + if right < array_length and array_to_sort[largest] < array_to_sort[right]: |
| 25 | + largest = right |
| 26 | + |
| 27 | + # If a larger element than root was found, swap with root so that root holds the new largest value |
| 28 | + if largest != index: |
| 29 | + array_to_sort[index], array_to_sort[largest] = array_to_sort[largest], array_to_sort[index] # swap |
| 30 | + |
| 31 | + # Re-build the heap under the new largest root node |
| 32 | + build_heap(array_to_sort, array_length, largest) |
| 33 | + |
| 34 | + |
| 35 | +def heap_sort(array_to_sort): |
| 36 | + """ |
| 37 | + Builds a max-heap, then continuously removes the largest element and re-builds the heap until sorted |
| 38 | + """ |
| 39 | + array_length = len(array_to_sort) |
| 40 | + |
| 41 | + # Build a max-heap to sort the elements into order |
| 42 | + for index in range(array_length // 2 - 1, -1, -1): |
| 43 | + build_heap(array_to_sort, array_length, index) |
| 44 | + |
| 45 | + # One by one extract elements |
| 46 | + for index in range(array_length - 1, 0, -1): |
| 47 | + array_to_sort[index], array_to_sort[0] = array_to_sort[0], array_to_sort[index] # swap |
| 48 | + build_heap(array_to_sort, index, 0) |
0 commit comments