-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07-shell-sort.js
49 lines (44 loc) · 1023 Bytes
/
07-shell-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
function shellSort(array) {
var swap = function(x, y) {
var temp = array[x];
array[x] = array[y];
array[y] = temp;
};
var length = array.length,
gap = Math.floor(length / 2);
while (gap > 0) {
for (var i = gap; i < length; i++) {
for (var j = i; 0 < j; j -= gap) {
if (array[j - gap] > array[j]) {
swap(j - gap, j);
} else {
break;
}
}
}
gap = Math.floor(gap / 2);
}
return array;
}
(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);
}(shellSort));