Understanding the Problem
We are given an array of numbers and we need to sort them in increasing order. Instead of using built-in sorting, we will implement Heap Sort, which is an efficient comparison-based sorting technique based on a binary heap data structure. Our goal is to understand how heap sort works step-by-step, including edge cases, using a beginner-friendly example.
Example to Understand
Let’s consider the input array: [4, 10, 3, 5, 1]. We want to sort this into: [1, 3, 4, 5, 10].
Step-by-Step Explanation
- Step 1: Build a Max Heap
A Max Heap is a binary tree where each parent node is greater than or equal to its children. For the array [4, 10, 3, 5, 1], we reorganize the array to follow the max heap property: [10, 5, 3, 4, 1].
- Step 2: Swap the Max Element with the Last
Swap the first element (maximum) with the last element: [1, 5, 3, 4, 10]. Now 10 is in its correct sorted position.
- Step 3: Heapify the Root
After removing the largest element (by reducing heap size), we heapify the new root (1) to maintain max heap: [5, 4, 3, 1, 10].
- Step 4: Repeat the Process
Continue the swap and heapify until the heap is reduced to one element:
- Swap 5 and 1 → [1, 4, 3, 5, 10], heapify → [4, 1, 3, 5, 10]
- Swap 4 and 3 → [3, 1, 4, 5, 10], heapify → [3, 1, 4, 5, 10]
- Swap 3 and 1 → [1, 3, 4, 5, 10], done.
- Final Sorted Array:
[1, 3, 4, 5, 10]
Handling Edge Cases
Case 1 - Single Element
Input: [1]
- Only one element is already sorted.
- No heap to build, return as-is:
[1]
Case 2 - Empty Array
Input: []
- Nothing to sort. Return empty array immediately.
Case 3 - Reverse Sorted Input
Input: [9, 8, 7, 6, 5]
- It’s already in max order, which helps form the max heap directly:
[9, 8, 7, 6, 5].
- Swap and heapify process will still work as normal.
- Final sorted output:
[5, 6, 7, 8, 9]
Case 4 - All Elements Are Same
Input: [5, 5, 5, 5]
- Heap sort works fine. Swapping and heapifying won't change positions, but the algorithm still runs.
- Sorted output is the same:
[5, 5, 5, 5]