#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

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

CaseTimeSpace
Best/Average/WorstO(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.

Why Heapifying Starts From the Middle

The build-heap loop begins at index n // 2 - 1 rather than at the start of the array. That index is the last node that has at least one child; everything after it is a leaf, and a single leaf is already a valid heap on its own. By heapifying backwards from this point toward the root, every node is fixed only after its children are already correct heaps, so each heapify call can safely sink a value into place.

This is why building the heap costs O(n) and not O(n log n). Most nodes sit near the bottom and sink only a level or two; the costly deep sinks happen for just a handful of nodes near the root.

A Short Dry Run

Take [4, 10, 3, 5, 1]. Building the max-heap rearranges it to [10, 5, 3, 4, 1]. Now swap the root 10 with the last slot to get [1, 5, 3, 4, 10], shrink the heap to the first four items, and heapify to get [5, 4, 3, 1]. Repeat: 5 moves to the end, then 4, then 3, leaving the array sorted as [1, 3, 4, 5, 10]. The sorted part grows from the right while the heap shrinks from the left, which is why no extra array is needed.

Heap Sort Compared With Quick Sort and Merge Sort

TraitHeap SortQuick SortMerge Sort
Worst caseO(n log n)O(n squared)O(n log n)
Extra memoryO(1)O(log n) stackO(n)
StableNoNoYes

Pick heap sort when a guaranteed upper bound and tiny memory use matter more than raw speed. In everyday sorting, quick sort usually runs faster because it touches memory in a more cache-friendly order, and merge sort is chosen when stability is required.

Mistakes to Watch For

  • Forgetting that heap sort is not stable — equal keys can swap order, which matters when sorting records by one field.
  • Using child indices 2*i+1 and 2*i+2 with a one-based array; those formulas assume zero-based indexing.
  • Passing the full length to heapify during extraction instead of the shrinking heap size, which pulls already-sorted values back in.

Takeaway: build once in linear time, then extract the maximum repeatedly. The whole method rests on keeping the max-heap property true after every swap.