-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08-merge-sort.js
58 lines (49 loc) · 1.12 KB
/
08-merge-sort.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
51
52
53
54
55
56
57
58
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;
}
function mergeSort(array) {
var len = array.length;
if (len < 2) {
return array;
}
var middle = Math.floor(len / 2),
left = array.slice(0, middle),
right = array.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
(function(sort) {
var random = function(max) {
var array = [];
for (var i = 0; i < max; i++) {
array[i] = i;
}
array.sort(function() {
return 0.5 - Math.random();
});
return array;
};
var test = function(count) {
for (var i = 0; i < count; i++) {
var array = random(10);
console.log('[No.' + (i + 1) + '] begin: ', array);
console.time('time');
console.log('[No.' + (i + 1) + '] end: ', sort(array));
console.timeEnd('time');
}
};
test(3);
}(mergeSort));