Implementing Heap Sort using vanilla JavaScript

Heap Sort is a comparison-based sorting algorithm that can be thought of as an improved selection sort. Like selection sort, it divides input into sorted and unsorted regions, but uses a binary heap data structure to efficiently find the maximum (or minimum) element.

How Heap Sort Works

Heap Sort works in two main phases:

  1. Build Max Heap: Convert the array into a max heap where parent nodes are larger than their children
  2. Extract Elements: Repeatedly remove the maximum element (root) and restore the heap property

Implementation

Here's a complete implementation of Heap Sort in JavaScript:

let len; // Global variable to track heap size

const constructHeap = (arr, ind) => {
    let left = 2 * ind + 1;
    let right = 2 * ind + 2;
    let max = ind;
    
    // Check if left child exists and is greater than parent
    if (left < len && arr[left] > arr[max]) {
        max = left;
    }
    
    // Check if right child exists and is greater than current max
    if (right < len && arr[right] > arr[max]) {
        max = right;
    }
    
    // If max is not the parent, swap and continue heapifying
    if (max != ind) {
        swap(arr, ind, max);
        constructHeap(arr, max);
    }
}

function swap(arr, index_A, index_B) {
    let temp = arr[index_A];
    arr[index_A] = arr[index_B];
    arr[index_B] = temp;
}

function heapSort(arr) {
    len = arr.length;
    
    // Build max heap (start from last parent node)
    for (let ind = Math.floor(len / 2) - 1; ind >= 0; ind--) {
        constructHeap(arr, ind);
    }
    
    // Extract elements one by one from heap
    for (let ind = arr.length - 1; ind > 0; ind--) {
        swap(arr, 0, ind); // Move current root to end
        len--; // Reduce heap size
        constructHeap(arr, 0); // Restore heap property
    }
}

// Example usage
const arr = [3, 0, 2, 5, -1, 4, 1];
console.log("Original array:", arr);
heapSort(arr);
console.log("Sorted array:", arr);
Original array: [ 3, 0, 2, 5, -1, 4, 1 ]
Sorted array: [ -1, 0, 1, 2, 3, 4, 5 ]

Step-by-Step Example

Let's trace through the algorithm with array [3, 0, 2, 5, -1, 4, 1]:

const arr = [3, 0, 2, 5, -1, 4, 1];
len = arr.length;

console.log("Building max heap:");
// Start from last parent node (index 2)
for (let ind = Math.floor(len / 2) - 1; ind >= 0; ind--) {
    console.log(`Heapifying at index ${ind}`);
    constructHeap([...arr], ind);
}

Time and Space Complexity

Aspect Complexity Explanation
Time (Average) O(n log n) Building heap: O(n), Extracting n elements: O(n log n)
Time (Worst) O(n log n) Consistent performance regardless of input
Space O(1) In-place sorting algorithm

Key Advantages

  • Guaranteed Performance: Always O(n log n) time complexity
  • In-Place: Requires only O(1) additional memory
  • Not Stable: Does not preserve relative order of equal elements

Conclusion

Heap Sort is an efficient, in-place sorting algorithm with guaranteed O(n log n) performance. While not stable, it's excellent for scenarios requiring predictable performance and minimal memory usage.

Updated on: 2026-03-15T23:19:00+05:30

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements