UNPKG

mergesort

Version:

Sort an array using the merge-sort algorithm.

51 lines (47 loc) 1.39 kB
module.exports = (function () { 'use strict'; /** * Sort an array using the merge sort algorithm. * * @param {function} comparatorFn The comparator function. * @param {array} arr The array to sort. * @returns {array} The sorted array. */ function mergeSort(comparatorFn, arr) { var len = arr.length, firstHalf, secondHalf; if (len >= 2) { firstHalf = arr.slice(0, len / 2); secondHalf = arr.slice(len / 2, len); return merge(comparatorFn, mergeSort(comparatorFn, firstHalf), mergeSort(comparatorFn, secondHalf)); } else { return arr.slice(); } } /** * The merge part of the merge sort algorithm. * * @param {function} comparatorFn The comparator function. * @param {array} arr1 The first sorted array. * @param {array} arr2 The second sorted array. * @returns {array} The merged and sorted array. */ function merge(comparatorFn, arr1, arr2) { var result = [], left1 = arr1.length, left2 = arr2.length; while (left1 > 0 && left2 > 0) { if (comparatorFn(arr1[0], arr2[0]) <= 0) { result.push(arr1.shift()); left1--; } else { result.push(arr2.shift()); left2--; } } if (left1 > 0) { result.push.apply(result, arr1); } else { result.push.apply(result, arr2); } return result; } return mergeSort; })();