logo
SEE ALGORITHMS
    Bubble Sort
    Insertion Sort
    Selection Sort
    Heap Sort
    Radix Sort
    Merge Sort
    Quick Sort

Heap Sort

Heap Sort is an efficient sorting algorithm that leverages a data structure called Binary Heap to organize and sort data. It works by first building a heap from the data and then repeatedly extracting the largest (or smallest) element from the heap and rebuilding the heap until all elements are sorted. This method is known for its reliable performance and in-place sorting capabilities, making it a strong choice for handling large datasets without requiring extra memory.

Things to Observe

  • Building the Heap: The first phase of the algorithm rearranges the array into a Max Heap, where the element at the root of any sub-tree is the largest.
  • Extracting the Max: In the second phase, watch how the largest element (at the root) is repeatedly swapped with the last element of the heap, and the heap is rebuilt. This process gradually builds the sorted array from the end.

Pseudocode

function heapify(i):
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2
    if left < n:
        if arr[left] > arr[largest]:
            largest = left
    if right < n:
        if arr[right] > arr[largest]:
            largest = right
    if largest != i:
        swap(i, largest)
        heapify(largest)
for i = (n / 2 - 1) down to 0:
    heapify(i)
for i = n - 1 down to 1:
    swap(0, i)
    heapify(0)
Select number of elements:  

Curious to Learn More?

Hand-picked resources to deepen your understanding

Beginner Friendly
Coding Interview Bootcamp: Algorithms + Data Structures

Learn essential data structures and algorithms step-by-step with practical JavaScript examples.

Practical Guide
JavaScript Algorithms & Data Structures Masterclass

Master DSA fundamentals, problem-solving techniques, and advanced structures using JavaScript.

Deep Dive
Master the Coding Interview: Data Structures + Algorithms

Prepare for top tech interviews with advanced DSA concepts and real-world coding challenges.

Learn DSA on Udemy
Learn DSA on Udemy
As an Udemy Associate, I earn from qualifying purchases.

© 2025 SEE Algorithms. Code licensed under MIT, content under CC BY-NC 4.0.