0
0
DSA Javascriptprogramming~30 mins

Heap Sort Algorithm in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Heap Sort Algorithm
📖 Scenario: You are working on a program that needs to sort a list of numbers efficiently. Heap sort is a great way to do this by using a special tree structure called a heap.Imagine you have a messy pile of books (numbers) and you want to arrange them from smallest to largest quickly. Heap sort helps you do this by organizing the pile so the biggest book is always on top, then taking it out one by one.
🎯 Goal: Build a heap sort algorithm in JavaScript that sorts an array of numbers in ascending order using a max heap.
📋 What You'll Learn
Create an array called arr with the exact numbers: 12, 11, 13, 5, 6, 7
Create a variable called n to store the length of arr
Write a function called heapify that maintains the max heap property for a subtree rooted at a given index
Write the main heap sort logic that builds the max heap and sorts the array
Print the sorted array after heap sort completes
💡 Why This Matters
🌍 Real World
Heap sort is used in systems where guaranteed O(n log n) sorting time is needed, such as in embedded systems or real-time applications.
💼 Career
Understanding heap sort helps in technical interviews and improves your grasp of efficient sorting algorithms used in software development.
Progress0 / 4 steps
1
Create the initial array
Create an array called arr with these exact numbers: 12, 11, 13, 5, 6, 7.
DSA Javascript
Hint

Use const arr = [...] with the exact numbers inside the square brackets.

2
Create a variable for array length
Create a variable called n and set it to the length of the array arr.
DSA Javascript
Hint

Use const n = arr.length; to get the array size.

3
Write the heapify function
Write a function called heapify that takes parameters arr, n, and i. It should maintain the max heap property for the subtree rooted at index i in the array arr of size n. Use variables largest, left, and right inside the function. Swap elements if needed and call heapify recursively.
DSA Javascript
Hint

Remember to check left and right children and swap if they are bigger than the current node.

4
Implement heap sort and print the sorted array
Write the heap sort logic: first build a max heap by calling heapify for all non-leaf nodes from Math.floor(n / 2) - 1 down to 0. Then extract elements one by one from the heap by swapping the root with the last element and calling heapify on the reduced heap. Finally, print the sorted array arr using console.log(arr).
DSA Javascript
Hint

Remember to build the max heap first, then swap the root with the last element and heapify the reduced heap repeatedly.