-
Notifications
You must be signed in to change notification settings - Fork 41
/
quicksortImprove.js
51 lines (43 loc) · 1.19 KB
/
quicksortImprove.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
console.log('quicksortImprove:')
/* input start */
var input = require('../../../generator/index').getRandomNumbers(40);
/* input end */
console.log('> input: ' + input);
// quicksortImprove
var delta = 5;
function quicksortImprove(input) {
sort(0, input.length - 1);
return input;
function sort(start, end) {
if(start + delta >= end) {
insertion(start, end);
return;
}
var mid = partition(start, end);
sort(start, mid - 1);
sort(mid + 1, end);
}
function partition(start, end) {
var i = start, j = end + 1, k = input[start];
while(true) {
while(input[++i] < k) if( i === end) break;
while(input[--j] > k) if( j === start) break;
if(i >= j) break;
input[i] = [input[j], input[j] = input[i]][0];
}
input[j] = [input[start], input[start] = input[j]][0];
return j;
}
function insertion(start, end) {
for(var i = start + 1, len = end - start; i < end; i++) {
for(var j = i; j > start; j--) {
if(input[j] < input[j - 1]) {
input[j] = [input[j - 1], input[j - 1] = input[j]][0];
}
}
}
}
}
/* output start */
console.log('> output: ' + quicksortImprove(input));
/* output end */