Problem Link - Heap sort Practice Problem in Heaps
Problem Statement
Given an array of integers, we need to sort it in ascending order using Heap Sort.
Approach
Heap Sort is a comparison-based sorting algorithm that works by:
- First, building a max-heap from the array.
- Then, repeatedly extracting the largest element from the heap and placing it at the end of the array.
Steps of the Algorithm
- Build the Max-Heap:
- Start from the last non-leaf node and call the
heapify
function for each node up to the root. - The
heapify
function ensures that the subtree rooted at the current index follows the max-heap property.
- Extract Elements One by One:
- Swap the root of the max-heap (the largest element) with the last element in the heap.
- Reduce the heap size by one and call
heapify
on the root to restore the max-heap property. - Repeat this process until the heap is reduced to a single element.
- For
heapify
see this - Insertion in a Heap Practice Problem in Heaps
Complexity
- Time Complexity: Building the max-heap takes
O(n)
. Each extraction operation involves aheapify
call, which takesO(logn)
and is performed n times, leading toO(n log n)
for the sorting phase. Thus, the overall time complexity isO(n log n)
. - Space Complexity: The space complexity is
O(1)
for in-place sorting, ignoring the input array space.