-
Notifications
You must be signed in to change notification settings - Fork 7
/
sort.js
126 lines (104 loc) · 2.79 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* 常见排序的JS 实现
* @author [email protected]
* @date 2013.10
*/
var Sort = {
//快速排序(递归)
quick: function(arr) {
var nLength = arr.length,
pivotIndex = Math.floor(nLength / 2),
pivot = arr.splice(pivotIndex, 1)[0],
left = [],
right = [];
if (nLength < 2) {
return arr;
}
for (var i = 0; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return arguments.callee(left).concat([pivot], arguments.callee(right));
},
//冒泡排序
bubble: function(arr) {
var nLength = arr.length;
if (nLength < 2) {
return arr;
}
for (var i = nLength - 1; i > 0; --i) {
for (var j = 0; j < i; ++j) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
},
//选择排序
selection: function(arr) {
var nLength = arr.length;
if (nLength < 2) {
return arr;
}
for (var i = 0; i < nLength; i++) {
var index = i;
for (var j = i + 1; j < nLength; j++) {
if (arr[j] < arr[index]) {
index = j;
}
}
if (i !== index) {
var temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
return arr;
},
//插入排序
insertion: function(arr) {
var nLength = arr.length;
if (nLength < 2) {
return arr;
}
for (var i = 1; i < nLength; ++i) {
var j = i,
value = arr[i];
while (j > 0 && arr[j - 1] > value) {
arr[j] = arr[j - 1];
--j;
}
if (j !== i) {
arr[j] = value;
}
}
return arr;
},
//希尔排序
shell: function(arr) {
var nLength = arr.length;
if (nLength < 2) {
return arr;
}
for (var step = nLength >> 1; step > 0; step >>= 1) {
for (var i = 0; i < step; ++i) {
for (var j = i + step; j < nLength; j += step) {
var k = j,
value = arr[j];
while (k >= step && arr[k - step] > value) {
arr[k] = arr[k - step];
k -= step;
}
arr[k] = value;
}
}
}
return arr;
}
};