Merge sort is a sorting algorithm that uses a divide-and-conquer approach to sort an array. It works by dividing the array into two halves, sorting each half, and then merging the two sorted halves back together.

Here is an example of a merge sort function implemented in JavaScript:

function mergeSort(arr) {
    if (arr.length < 2) {
        return arr;
    }
    var middle = Math.floor(arr.length / 2);
    var left = arr.slice(0, middle);
    var right = arr.slice(middle);
    return merge(mergeSort(left), mergeSort(right));
}
function merge(left, right) {
    var result = [];
    while (left.length && right.length) {
        if (left[0] <= right[0]) {
            result.push(left.shift());
        } else {
            result.push(right.shift());
        }
    }
    while (left.length) result.push(left.shift());
    while (right.length) result.push(right.shift());
    return result;
}

You can use it like this:

var arr = [38, 27, 43, 3, 9, 82, 10];
console.log(mergeSort(arr));

This will sort the array and return it in ascending order.

Note: The above implementation is the most basic version of the merge sort algorithm, it is not optimized.

Also Read:

Categorized in: