-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
50 lines (47 loc) · 1.35 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;
})();