</>
Skip to content
DSA lessons (35/55)

DSA — Heap Sort

What is Heap Sort?

Uses a binary heap to sort elements by building a max heap and extracting maximum.

def heapify(arr, n, i):
    largest = i
    left = 2 * i + 1
    right = 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)
    
    # Build max heap
    for i in range(n // 2 - 1, -1, -1):
        heapify(arr, n, i)
    
    # Extract elements
    for i in range(n - 1, 0, -1):
        arr[0], arr[i] = arr[i], arr[0]
        heapify(arr, i, 0)
    
    return arr

Time Complexity

CaseComplexity
BestO(n log n)
AverageO(n log n)
WorstO(n log n)

Characteristics

  • Not stable
  • In-place
  • Consistent performance
  • Good for priority queues

Mini Practice

  1. Implement heap sort
  2. Build max heap
  3. Sort in descending order
  4. Compare with quick sort

Up Next

Continue with Counting Sort — non-comparison sort.

Related Topics

Frequently Asked Questions about Heap Sort

What is Heap Sort in DSA?

Heap Sort is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Heap Sort?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Heap Sort.

Why is Heap Sort important in DSA?

Heap Sort is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.