TypeScript Program to Implement Merge Sort

TypeScript Program to Implement Merge Sort

Merge Sort is one of the most important and widely used sorting algorithms in computer science. Unlike simple sorting methods, Merge Sort follows a smart strategy called “divide and conquer.” This means it breaks a large problem into smaller parts, solves them separately, and then combines the results. Because of this approach, Merge Sort is much faster and more reliable than basic algorithms when working with large amounts of data.

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

Merge Sort matters because it guarantees good performance even when the data grows very large. It is commonly used in real-world systems such as databases, file sorting tools, and backend services where speed and consistency are important. Learning how to write a Merge Sort program in TypeScript helps beginners understand recursion, array handling, and efficient problem solving. These skills are very valuable for modern web and software development.

Program 1: Basic Recursive Merge Sort in TypeScript

This program shows the classic and most common way to implement Merge Sort. It uses recursion to divide the array and a helper function to merge sorted parts. This is the standard approach taught to beginners.

function merge(left: number[], right: number[]): number[] {

    let result: number[] = [];
    let i = 0;
    let j = 0;

    while (i < left.length && j < right.length) {

        if (left[i] < right[j]) {

            result.push(left[i]);
            i++;

        } else {

            result.push(right[j]);
            j++;

        }

    }

    return result.concat(left.slice(i)).concat(right.slice(j));

}

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

    if (arr.length <= 1) {
        return arr;
    }

    const mid = Math.floor(arr.length / 2);
    const left = mergeSort(arr.slice(0, mid));
    const right = mergeSort(arr.slice(mid));

    return merge(left, right);

}

let numbers: number[] = [38, 27, 43, 3, 9, 82, 10];

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

This program works by repeatedly splitting the array until each part has only one element. Then it merges those parts back together in sorted order. Beginners can understand this by thinking of it as sorting small pieces first and then combining them to form a fully sorted array.

Program 2: Merge Sort Using Separate Merge Function

This version clearly separates the merge logic from the sorting logic. It helps beginners see how breaking code into smaller functions improves readability and organization.

function mergeArrays(a: number[], b: number[]): number[] {

    let sorted: number[] = [];

    while (a.length && b.length) {

        if (a[0] <= b[0]) {
            sorted.push(a.shift() as number);
        } else {
            sorted.push(b.shift() as number);
        }

    }

    return sorted.concat(a, b);

}

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

    if (arr.length < 2) {
        return arr;
    }

    const middle = Math.floor(arr.length / 2);
    const left = mergeSortSimple(arr.slice(0, middle));
    const right = mergeSortSimple(arr.slice(middle));

    return mergeArrays(left, right);

}

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

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

This program shows how two sorted arrays are merged by comparing their first elements. Beginners can clearly see how the merge step works without being distracted by too much logic in one place. This approach also teaches the value of clean and modular code.

Program 3: Merge Sort with Index-Based Merging

This program avoids modifying the original arrays during merging. Instead, it uses index counters, which is closer to how Merge Sort is implemented in performance-focused environments.

function mergeWithIndex(left: number[], right: number[]): number[] {

    let result: number[] = [];
    let i = 0;
    let j = 0;

    while (i < left.length && j < right.length) {

        if (left[i] < right[j]) {
            result.push(left[i++]);
        } else {
            result.push(right[j++]);
        }

    }

    while (i < left.length) {
        result.push(left[i++]);
    }

    while (j < right.length) {
        result.push(right[j++]);
    }

    return result;

}

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

    if (arr.length <= 1) {
        return arr;
    }

    const mid = Math.floor(arr.length / 2);

    return mergeWithIndex(
        mergeSortIndexed(arr.slice(0, mid)),
        mergeSortIndexed(arr.slice(mid))
    );

}

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

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

This version helps beginners understand how pointers or indexes move through arrays. It is useful for learning how Merge Sort works internally without changing the original data structures.

Program 4: Merge Sort in Descending Order

This program sorts the array in descending order instead of ascending order. It shows how flexible Merge Sort is and how small changes can affect the result.

function mergeDesc(left: number[], right: number[]): number[] {

    let result: number[] = [];

    while (left.length && right.length) {

        if (left[0] >= right[0]) {
            result.push(left.shift() as number);
        } else {
            result.push(right.shift() as number);
        }

    }

    return result.concat(left, right);

}

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

    if (arr.length <= 1) {
        return arr;
    }

    const mid = Math.floor(arr.length / 2);
    const left = mergeSortDesc(arr.slice(0, mid));
    const right = mergeSortDesc(arr.slice(mid));

    return mergeDesc(left, right);

}

let items: number[] = [20, 35, 15, 7, 55, 1];

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

By changing the comparison logic, this program places larger values first. Beginners can see how Merge Sort can easily be adapted to different sorting needs, which is very helpful in real-world applications.

Program 5: Merge Sort Wrapper for Cleaner Usage

This final program adds a wrapper function to make Merge Sort easier to use. It is useful when writing larger programs where clarity matters.

function mergeCore(left: number[], right: number[]): number[] {

    let result: number[] = [];
    let i = 0;
    let j = 0;

    while (i < left.length && j < right.length) {

        if (left[i] < right[j]) {
            result.push(left[i++]);
        } else {
            result.push(right[j++]);
        }

    }

    return result.concat(left.slice(i), right.slice(j));

}

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

    if (arr.length <= 1) {
        return arr;
    }

    const mid = Math.floor(arr.length / 2);
    const leftPart = mergeSortWrapper(arr.slice(0, mid));
    const rightPart = mergeSortWrapper(arr.slice(mid));

    return mergeCore(leftPart, rightPart);

}

let nums: number[] = [31, 41, 59, 26, 53, 58];

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

This version focuses on readability and structure. Beginners can easily reuse the wrapper function without worrying about internal details. It is a good example of writing clean and maintainable TypeScript code.

Frequently Asked Questions (FAQ)

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

Q1. Why is Merge Sort faster than simple sorting algorithms?
Merge Sort divides the data into smaller parts and sorts them efficiently, which makes it much faster for large datasets.

Q2. Is Merge Sort used in real applications?
Yes, Merge Sort is widely used in databases, file systems, and many backend systems.

Q3. Does Merge Sort work with negative numbers?
Yes, Merge Sort works perfectly with negative numbers as long as comparisons are done correctly.

Q4. Is recursion required for Merge Sort?
Merge Sort is usually implemented using recursion, but the concept can also be applied iteratively with more complex logic.

Q5. What should I learn after Merge Sort?
After Merge Sort, beginners often move on to Quick Sort, Heap Sort, and advanced data structures.

Conclusion

Merge Sort is a powerful and reliable sorting algorithm that every beginner should learn. In this article, we explored several TypeScript programs that implement Merge Sort using recursion, helper functions, index-based merging, and even reverse sorting. Each example showed how the same core idea can be applied in different ways.

If you are new to TypeScript or sorting algorithms, try running these programs and experimenting with different data values. Practice will help you understand the divide-and-conquer approach more deeply. Keep learning, keep coding, and enjoy building strong foundations in programming.

Scroll to Top