sort.js
1.23 KB
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
51
52
53
54
55
/**
* Merge sort (http://en.wikipedia.org/wiki/Merge_sort)
*/
function mergeSort(arr, compareFn) {
if (arr == null) {
return [];
} else if (arr.length < 2) {
return arr;
}
if (compareFn == null) {
compareFn = defaultCompare;
}
var mid, left, right;
mid = ~~(arr.length / 2);
left = mergeSort( arr.slice(0, mid), compareFn );
right = mergeSort( arr.slice(mid, arr.length), compareFn );
return merge(left, right, compareFn);
}
function defaultCompare(a, b) {
return a < b ? -1 : (a > b? 1 : 0);
}
function merge(left, right, compareFn) {
var result = [];
while (left.length && right.length) {
if (compareFn(left[0], right[0]) <= 0) {
// if 0 it should preserve same order (stable)
result.push(left.shift());
} else {
result.push(right.shift());
}
}
if (left.length) {
result.push.apply(result, left);
}
if (right.length) {
result.push.apply(result, right);
}
return result;
}
module.exports = mergeSort;