Introduction
Sorting a list of items quickly and efficiently is a common problem. Heap sort solves this by using a special tree structure to organize and sort data step-by-step.
Imagine organizing a pile of books so the heaviest book is always on top. You remove the heaviest book one by one, then rearrange the pile so the next heaviest is on top again. This way, you sort the books from heaviest to lightest.
┌─────────┐
│ 50 │
├─────────┤
┌───┴───┐ ┌───┴───┐
│ 30 │ │ 40 │
┌─┴─┐ ┌─┴─┐ ┌─┴─┐ ┌─┴─┐
│10 │ │20 │ │35 │ │25 │def heapify(arr, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: largest = right if largest != i: arr[i], arr[largest] = arr[largest], arr[i] heapify(arr, n, largest) def heap_sort(arr): n = len(arr) for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) for i in range(n - 1, 0, -1): arr[0], arr[i] = arr[i], arr[0] heapify(arr, i, 0) arr = [12, 11, 13, 5, 6, 7] heap_sort(arr) print(arr)