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.
How Heap Sort Works
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
Let's sort the array: [4, 10, 3, 5, 1].
1. Build a Max Heap:
○ Start with the array: [4, 10, 3, 5, 1].
Transform it into a max heap:
basic
Copy
10
/ \
5 3
/ \
4 1
○
○ 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:
Swap 5 and 1: [1, 4, 3, 5, 10], then re-heapify:
Copy
4
/\
1 3
○
○ The array becomes: [4, 3, 1, 5, 10].
Swap 4 and 1: [1, 3, 4, 5, 10], then re-heapify:
Copy
3
/
1
○
○ The array is now: [3, 1, 4, 5, 10].
○ Finally, swap 3 and 1: [1, 3, 4, 5, 10].
4. Final Sorted Array:
○ The final sorted array is: [1, 3, 4, 5, 10].
Time Complexity Analysis
1. Time Complexity:
○ Best Case: O(nlogn)O(n \log n)O(nlogn)
■ This occurs during the heap construction and sorting phases.
○ Average Case: O(nlogn)O(n \log n)O(nlogn)
■ Heap sort consistently performs O(nlogn)O(n \log n)O(nlogn) due to the
nature of heap operations.
○ Worst Case: O(nlogn)O(n \log n)O(nlogn)
■ In the worst-case scenario, the time complexity remains O(nlogn)O(n \log
n)O(nlogn).
2. Space Complexity:
○ Space Complexity: O(1)O(1)O(1)
■ Heap Sort is an in-place sorting algorithm, meaning it requires a constant
amount of additional space beyond the input array.
3. Stability:
○ 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.