Heap Sort Algorithm in Data Structure — Working, Implementation and Applications
Heap Sort is a comparison-based sorting algorithm that uses a Binary Heap data structure. It first builds a max-heap from the input data, then repeatedly extracts the maximum element and rebuilds the heap until the array is sorted.
How It Works
- Build a max-heap from the input array, so the largest element is at the root.
- Swap the root (maximum) with the last element of the heap.
- Reduce the heap size by one and 'heapify' the root to restore the max-heap property.
- Repeat until the heap size is 1 — the array is now sorted in ascending order.
def heapify(arr, n, i):
largest = i
left, right = 2 * i + 1, 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
for i in range(n - 1, 0, -1):
arr[0], arr[i] = arr[i], arr[0]
heapify(arr, i, 0)
return arr
Complexity
| Case | Time | Space |
|---|---|---|
| Best/Average/Worst | O(n log n) | O(1) |
Applications
- Systems requiring guaranteed O(n log n) worst-case performance (unlike Quick Sort).
- Priority queue implementations.
- Finding the k largest/smallest elements in a dataset.
- Used in embedded and real-time systems where predictable performance matters.
PreviousShell Sort in Data Structure — Algorithm, Visualization and Complexity
Next Tower of Hanoi in Data Structure
Ready to master Data Structures & Algorithms?
Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.
.png)