Heap Sort
Heap Sort
Definition
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure. It
creates a max heap (or min heap) from the input data and then repeatedly extracts the
maximum (or minimum) element to build a sorted array.
1. Build a Heap: Convert the input array into a max heap (or min heap).
2. Sort the Array: Repeatedly extract the maximum (or minimum) element from the heap
and place it at the end of the array.
3. Heapify: After removing the root of the heap, re-heapify the remaining elements to
maintain the heap property.
Example
○
○ The array representation of the max heap is: [10, 5, 3, 4, 1].
2. Sort the Array:
○ Swap the root (maximum element) with the last element and reduce the heap
size by one:
■ Swap 10 and 1: [1, 5, 3, 4, 10].
Re-heapify the remaining elements:
Copy
5
/ \
4 3
/
1
○
○ The array is now: [5, 4, 3, 1, 10].
3. Repeat the Process:
○
○ The array becomes: [4, 3, 1, 5, 10].
○
○ The array is now: [3, 1, 4, 5, 10].
○ Finally, swap 3 and 1: [1, 3, 4, 5, 10].
4. Final Sorted Array:
○ Heap Sort is not a stable sorting algorithm. Equal elements may not maintain
their relative order after sorting.
4. In-place Sorting:
○ Heap Sort is an in-place algorithm because it requires only a small, fixed amount
of additional storage space.
Conclusion
Heap Sort is an efficient sorting algorithm with a guaranteed time complexity of O(nlogn)O(n \log
n)O(nlogn) in all cases. Its in-place nature makes it memory efficient, although it lacks stability.
Heap Sort is particularly useful for large datasets and scenarios where memory usage is a
concern, making it a valuable tool in the sorting arsenal.