Intermediate 25 min

Implementation

Let’s code heap sort. It has two main phases: build heap, then extract.

Complete Implementation


              function heapSort(arr) {
const n = arr.length;

// Build max heap
for (let i = Math.floor(n / 2) - 1; i >= 0; i--) {
  heapify(arr, n, i);
}

// Extract elements one by one
for (let i = n - 1; i > 0; i--) {
  // Move root to end
  [arr[0], arr[i]] = [arr[i], arr[0]];
  
  // Heapify reduced heap
  heapify(arr, i, 0);
}

return arr;
}

function heapify(arr, n, i) {
let largest = i;
const left = 2 * i + 1;
const right = 2 * i + 2;

if (left < n && arr[left] > arr[largest]) {
  largest = left;
}

if (right < n && arr[right] > arr[largest]) {
  largest = right;
}

if (largest !== i) {
  [arr[i], arr[largest]] = [arr[largest], arr[i]];
  heapify(arr, n, largest);
}
}
            

Try It Yourself

🟨 JavaScript Heap Sort Implementation
📟 Console Output
Run code to see output...

Code Explanation

  1. Build heap: Convert array to max heap

    • Start from last non-leaf node
    • Heapify each node bottom-up
  2. Extract and sort: Repeatedly extract maximum

    • Swap root with last element
    • Reduce heap size
    • Heapify root to restore property

Edge Cases

  • Empty array: Returns empty array
  • Single element: Already sorted
  • Already sorted: Still builds heap and extracts

What’s Next?

Now that you can implement it, let’s analyze its performance and complexity.