TypeScript Program to Implement Heap Sort

TypeScript Program to Implement Heap Sort

Heap Sort is a powerful and efficient sorting algorithm that is often introduced after learning simpler methods like Bubble Sort or Selection Sort. It is based on a special tree-like structure called a heap, which helps the algorithm always pick the largest or smallest value quickly. Because of this smart structure, Heap Sort performs very well even when the data becomes large.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Heap Sort matters because it combines good performance with predictable behavior. It is commonly used in systems where memory usage must stay low, such as operating systems, embedded systems, and performance-critical applications. Learning Heap Sort in TypeScript helps beginners understand advanced ideas like tree logic inside arrays, index calculations, and efficient sorting. These skills are very useful for anyone who wants to grow beyond basic algorithms.

Program 1: Basic Heap Sort Using Max Heap

This program shows the standard and most commonly used Heap Sort approach. It builds a max heap and then sorts the array by repeatedly moving the largest value to the end.

function heapify(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let 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);

    }

}

function heapSort(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapify(arr, i, 0);
    }

    return arr;

}

let numbers: number[] = [12, 11, 13, 5, 6, 7];

console.log("Sorted array:", heapSort(numbers));

This program works by first converting the array into a max heap, where the largest value is always at the top. Then the largest value is moved to the end, and the heap is rebuilt. Beginners can understand this as repeatedly picking the biggest number and placing it where it belongs.

Program 2: Heap Sort with Clear Step Separation

This version separates heap building and sorting more clearly. It helps beginners follow the logic without feeling overwhelmed.

function heapify(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let 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);

    }

}

function buildMaxHeap(arr: number[]): void {

    let n = arr.length;

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

}

function heapSortSteps(arr: number[]): number[] {

    buildMaxHeap(arr);

    for (let i = arr.length - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapify(arr, i, 0);
    }

    return arr;

}

let data: number[] = [4, 10, 3, 5, 1];

console.log("Sorted array:", heapSortSteps(data));

By separating steps, this program makes Heap Sort easier to read and understand. Beginners can clearly see when the heap is built and when sorting begins. This style is helpful for learning and debugging.

Program 3: Heap Sort Using Recursive Heapify

This program focuses on the recursive nature of heapify. It is useful for beginners who want to practice recursion in a real algorithm.

function heapifyRecursive(arr: number[], size: number, root: number): void {

    let largest = root;
    let left = 2 * root + 1;
    let right = 2 * root + 2;

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

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

    if (largest !== root) {

        [arr[root], arr[largest]] = [arr[largest], arr[root]];

        heapifyRecursive(arr, size, largest);

    }

}

function heapSortRecursive(arr: number[]): number[] {

    let size = arr.length;

    for (let i = Math.floor(size / 2) - 1; i >= 0; i--) {
        heapifyRecursive(arr, size, i);
    }

    for (let i = size - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapifyRecursive(arr, i, 0);
    }

    return arr;

}

let values: number[] = [9, 4, 7, 1, 3, 6];

console.log("Sorted array:", heapSortRecursive(values));

This version shows how recursion helps fix the heap when a swap happens. Beginners can see how the function keeps calling itself until the heap rule is restored. It is a great way to combine sorting and recursion learning.

Program 4: Heap Sort in Descending Order Using Min Heap

This program sorts the array in descending order by using a min heap instead of a max heap.

function minHeapify(arr: number[], n: number, i: number): void {

    let smallest = i;
    let left = 2 * i + 1;
    let right = 2 * i + 2;

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

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

    if (smallest !== i) {
        [arr[i], arr[smallest]] = [arr[smallest], arr[i]];
        minHeapify(arr, n, smallest);
    }

}

function heapSortDescending(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        minHeapify(arr, i, 0);
    }

    return arr;

}

let items: number[] = [2, 8, 5, 3, 9, 1];

console.log("Sorted array in descending order:", heapSortDescending(items));

By changing the heap type, this program produces a different sorting order. Beginners can see how flexible Heap Sort is and how small logic changes affect results.

Program 5: Heap Sort with Wrapper Function

This version wraps Heap Sort inside a clean function that can be reused easily. It focuses on readability and practical usage.

function heapify(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let 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);

    }

}

function heapSort(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapify(arr, i, 0);
    }

    return arr;

}

function heapSortWrapper(arr: number[]): number[] {

    let copy = [...arr];
    return heapSort(copy);

}

let nums: number[] = [14, 3, 27, 10, 35, 19];

console.log("Sorted array:", heapSortWrapper(nums));

This program avoids modifying the original array by working on a copy. Beginners learn good coding habits that are useful in real applications where data safety matters.

Program 6: Heap Sort Handling Floating Point Numbers

Heap Sort works naturally with floating point numbers, and this program demonstrates that clearly.

function heapify(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let 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);

    }

}

function heapSort(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapify(arr, i, 0);
    }

    return arr;

}

let floatNumbers: number[] = [3.5, 1.2, 4.8, 2.1, 0.9];

console.log("Sorted array:", heapSort(floatNumbers));

This example shows that Heap Sort does not need special changes for decimal values. Beginners can confidently use it for real-world numeric data.

Program 7: Heap Sort with Negative Numbers

Heap Sort also handles negative numbers correctly. This program demonstrates that behavior.

function heapify(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let 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);

    }

}

function heapSort(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapify(arr, i, 0);
    }

    return arr;

}

let negativeNumbers: number[] = [-4, 10, -3, 5, 1];

console.log("Sorted array:", heapSort(negativeNumbers));

The algorithm treats negative numbers just like any other values. Beginners can see that no extra logic is required, which makes Heap Sort reliable.

Program 8: Heap Sort with Mixed Numbers

This program sorts an array containing both negative and floating point numbers.

function heapify(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let 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);

    }

}

function heapSort(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapify(arr, i, 0);
    }

    return arr;

}

let mixedNumbers: number[] = [3.2, -1.5, 4, 0, -7.8, 2.6];

console.log("Sorted array:", heapSort(mixedNumbers));

This example shows Heap Sort working with mixed numeric data. It helps beginners trust the algorithm in practical scenarios.

Program 9: Heap Sort with Custom Comparison Logic

This final program tweaks Heap Sort to support custom comparison logic. It is useful when sorting numbers based on absolute value.

function heapifyCustom(arr: number[], n: number, i: number): void {

    let largest = i;
    let left = 2 * i + 1;
    let right = 2 * i + 2;

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

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

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

}

function heapSortCustom(arr: number[]): number[] {

    let n = arr.length;

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

    for (let i = n - 1; i > 0; i--) {
        [arr[0], arr[i]] = [arr[i], arr[0]];
        heapifyCustom(arr, i, 0);
    }

    return arr;

}

let customData: number[] = [-10, 2, -3, 7, -5];

console.log("Sorted by absolute value:", heapSortCustom(customData));

This program shows how Heap Sort can be adapted for special needs. Beginners learn that algorithms can be customized beyond default behavior.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Heap Sort in TypeScript in a simple and friendly way.

Q1. Why is Heap Sort considered efficient?
Heap Sort always runs in predictable time and does not slow down badly with large data.

Q2. Is Heap Sort used in real systems?
Yes, Heap Sort is used in operating systems, priority queues, and performance-critical software.

Q3. Does Heap Sort need extra memory?
Heap Sort uses very little extra memory because it sorts the array in place.

Q4. Is Heap Sort better than Quick Sort?
Heap Sort is more predictable, while Quick Sort is often faster in practice. Both are important.

Q5. What should I learn after Heap Sort?
After Heap Sort, beginners often explore priority queues, tree structures, and algorithm optimization.

Conclusion

Heap Sort is a strong and reliable sorting algorithm that every serious learner should understand. In this article, we explored many TypeScript programs that implement Heap Sort using different styles, including recursion, descending order, mixed numbers, and custom logic. Each example showed how flexible and practical Heap Sort can be.

If you are learning TypeScript or algorithms, try running these programs and modifying the data. Practice will help you understand heap logic more deeply. Keep learning, keep experimenting, and enjoy building confidence in your programming journey.

Scroll to Top