📘Educational
Heap Sort Algorithm —
Document
📌 Overview
Heap Sort is a comparison-based sorting algorithm that uses a binary heap
data structure to sort elements. It is an in-place, not stable sorting technique
with a time complexity of O(n log n) in all cases (best, average, and worst).
Heap sort typically builds a Max Heap to sort the array in ascending order, or a
Min Heap for descending order.
🏗️ What is a Heap?
A heap is a special binary tree-based data structure that satisfies the heap
property:
Max Heap: Every parent node is greater than or equal to its children.
Min Heap: Every parent node is less than or equal to its children.
Heaps are commonly implemented as arrays, where:
The parent of a node at index i is at i // 2
The left child is at 2 * i
The right child is at 2 * i + 1
(Using 1-based index)
🔄 How Heap Sort Works
Step-by-Step Algorithm:
1. Build a Max Heap from the input array.
2. Swap the first element (maximum) with the last.
3. Reduce the heap size by 1.
4. Heapify the root to maintain the Max Heap property.
5. Repeat steps 2–4 until the heap size is 1.
📘 Heap Sort Algorithm — Educational Document
1
🧾 Pseudocode
HEAP_SORT(arr):
BUILD_MAX_HEAP(arr)
for i from length(arr) - 1 down to 1:
swap arr[0] with arr[i]
MAX_HEAPIFY(arr, 0, i)
BUILD_MAX_HEAP(arr):
for i from floor(length(arr)/2) down to 0:
MAX_HEAPIFY(arr, i, length(arr))
MAX_HEAPIFY(arr, i, heap_size):
left = 2*i + 1
right = 2*i + 2
largest = i
if left < heap_size and arr[left] > arr[largest]:
largest = left
if right < heap_size and arr[right] > arr[largest]:
largest = right
if largest != i:
swap arr[i] and arr[largest]
MAX_HEAPIFY(arr, largest, heap_size)
🧪 Example
Input array:
[4, 10, 3, 5, 1]
1. Build Max Heap: [10, 5, 3, 4, 1]
2. Swap 10 with 1 → [1, 5, 3, 4, 10]
3. Heapify → [5, 4, 3, 1, 10]
4. Swap 5 with 1 → [1, 4, 3, 5, 10]
5. Heapify → [4, 1, 3, 5, 10] → continue...
Final sorted array:
📘 Heap Sort Algorithm — Educational Document
2
[1, 3, 4, 5, 10]
⏱️ Time and Space Complexity
Case
Time Complexity
Best
O(n log n)
Average
O(n log n)
Worst
O(n log n)
Space
O(1)
In-place: Yes
Stable: No (element order is not preserved)
✅ Advantages
Consistent time complexity of O(n log n).
No additional memory required (space complexity O(1)).
❌ Disadvantages
Not stable.
More complex than simpler algorithms like Insertion or Bubble Sort for small
datasets.
📚 When to Use Heap Sort?
When consistent performance is needed regardless of input distribution.
When you need a sort that doesn't require extra memory.
Would you like me to include this in a Markdown file or export as a PDF for
learning or presentation use?
📘 Heap Sort Algorithm — Educational Document
3