Heap Sort
📚 Heap Sort
-
Heap Sort is a comparison-based sorting technique based on a special tree structure called a Heap.
-
A Heap is a complete binary tree that satisfies the heap property.
-
In a Max Heap, for every node
i
, the value ofi
is greater than or equal to the values of its children.
👉 In Heap Sort:
-
We build a Max Heap from the input data.
-
The largest item is stored at the root of the heap.
-
Replace it with the last item of the heap and reduce the heap size by 1.
-
Heapify the root again to maintain the Max Heap property.
-
Repeat this until the heap size is 1.
🛠️ Algorithm for Heap Sort
-
Build Max Heap from input array.
-
Repeat until heap size > 1:
-
Swap the root (maximum element) with the last element.
-
Reduce heap size by 1.
-
Heapify the root to restore heap property.
-
🔥 Heapify Algorithm (Maintain Max Heap property)
📈 Example:
Input Array:
[4, 10, 3, 5, 1]
Step 1: Build a Max Heap
Max Heap:
[10, 5, 3, 4, 1]
Step 2: Sort
-
Swap 10 and 1 →
[1, 5, 3, 4, 10]
-
Heapify →
[5, 4, 3, 1, 10]
-
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]
-
Now sorted!
Final Sorted Array:
[1, 3, 4, 5, 10]
📌 Important points:
Feature | Details |
---|---|
Time Complexity | O(n log n) in all cases |
Space Complexity | O(1) (in-place) |
Stable? | ❌ No, Heap Sort is not stable |
Best for? | Large datasets when memory usage is critical |
Comments
Post a Comment