JavaScript Program to Implement Merge Sort

JavaScript Program to Implement Merge Sort

Merge Sort is a powerful and efficient sorting algorithm that is widely used in real-world software. Unlike simple sorting methods, Merge Sort uses a smart idea called divide and conquer. This means it breaks a large problem into smaller parts, solves them one by one, and then joins the results together. In JavaScript, Merge Sort is very popular because it performs well even when the data size 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

This algorithm matters because it is fast, reliable, and predictable. Merge Sort is often used in applications that need to sort large amounts of data, such as databases, search engines, and file systems. For beginners, learning Merge Sort is an important step because it introduces recursion, problem-solving skills, and a more professional way of thinking about algorithms.

Program 1: Merge Sort using basic recursion

This program shows the classic way to implement Merge Sort in JavaScript using recursion. It breaks the array into smaller pieces and then merges them back in sorted order.

function mergeSort(arr) {

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

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

    return merge(mergeSort(left), mergeSort(right));

}

function merge(left, right) {

    let result = [];
    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));

}

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

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

This program works by splitting the array again and again until each part has only one element. Then it merges those parts back together in sorted order. Beginners find this useful because it clearly shows how recursion and merging work together to solve a bigger problem.

Program 2: Merge Sort with clear helper functions

This version separates the logic into clean helper functions to make the code easier to read. It helps beginners focus on understanding each step.

function sortArray(arr) {

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

    let middle = Math.floor(arr.length / 2);
    let leftPart = arr.slice(0, middle);
    let rightPart = arr.slice(middle);

    return combine(sortArray(leftPart), sortArray(rightPart));

}

function combine(left, right) {

    let sorted = [];

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

        if (left[0] <= right[0]) {
            sorted.push(left.shift());
        } else {
            sorted.push(right.shift());
        }

    }

    return sorted.concat(left, right);

}

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

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

This program keeps things simple by clearly separating splitting and merging. It is helpful for beginners because each function has one clear job. This makes the algorithm easier to understand and remember.

Program 3: Merge Sort using index-based merging

This program avoids changing the original arrays and uses index values instead. It is slightly more advanced but still beginner-friendly.

function mergeSortIndex(arr) {

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

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

    let merged = [];
    let i = 0;
    let j = 0;

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

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

    }

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

}

let values = [50, 23, 9, 18, 61, 32];

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

This version shows how Merge Sort can be written without modifying arrays directly. Beginners can learn how indexes work and how data flows through the algorithm. It also feels closer to how Merge Sort is written in performance-focused programs.

Program 4: Merge Sort in descending order

This example sorts the array from largest to smallest. It helps learners understand how comparison logic affects the final result.

function mergeSortDesc(arr) {

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

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

    return mergeDesc(left, right);

}

function mergeDesc(left, right) {

    let result = [];

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

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

    }

    return result.concat(left, right);

}

let scores = [15, 30, 10, 50, 20];

console.log("Sorted array (descending):", mergeSortDesc(scores));

This program simply reverses the comparison condition to change the sorting order. Beginners can easily experiment with this version to see how small changes affect the output. It also builds confidence in working with conditions.

Program 5: Merge Sort wrapped in a reusable function

This version focuses on reusability and clean structure. It shows how Merge Sort can be used as a utility function in real projects.

function mergeSortReusable(arr) {

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

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

    return mergeReusable(mergeSortReusable(left), mergeSortReusable(right));

}

function mergeReusable(left, right) {

    let result = [];
    let leftIndex = 0;
    let rightIndex = 0;

    while (leftIndex < left.length && rightIndex < right.length) {

        if (left[leftIndex] < right[rightIndex]) {

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

        } else {

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

        }

    }

    return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));

}

let items = [7, 2, 9, 1, 5, 3];

console.log("Sorted array:", mergeSortReusable(items));

This program shows how Merge Sort is commonly written in professional JavaScript code. Beginners can reuse this function with different arrays and understand how clean structure improves readability. It is a great example of writing maintainable code.

Frequently Asked Questions (FAQ)

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

Q1. What is Merge Sort in JavaScript?
Merge Sort is an efficient sorting algorithm that divides an array into smaller parts, sorts them, and merges them back together in order.

Q2. Why is Merge Sort faster than Bubble Sort or Selection Sort?
Merge Sort reduces the number of comparisons by dividing the problem into smaller pieces. This makes it much faster for large arrays.

Q3. Is Merge Sort used in real applications?
Yes, Merge Sort is widely used in real systems, especially when working with large data sets and stable sorting is needed.

Q4. Does Merge Sort use recursion?
Yes, most Merge Sort implementations use recursion to divide the array into smaller parts. This is one reason it is great for learning recursion.

Q5. Should beginners learn Merge Sort?
Yes, beginners should learn Merge Sort after understanding basic sorting algorithms. It teaches advanced thinking and problem-solving skills.

Conclusion

Merge Sort is an important milestone for anyone learning JavaScript algorithms. It introduces powerful ideas like divide and conquer, recursion, and efficient merging. Even though it looks more complex than simple sorting methods, breaking it down makes it easy to understand step by step.

The best way to master Merge Sort is to practice it with different data and variations. Try sorting numbers, changing the order, and rewriting the code in your own style. With time and practice, Merge Sort will help you feel more confident and ready to tackle advanced JavaScript algorithms.

Scroll to Top