Skip to content

Commit 035b08b

Browse files
committed
希尔排序 📁
1 parent aa8f606 commit 035b08b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

javascript/algorithm/sort/Shell.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 希尔排序
3+
* 1.计算出步长 step,step = length / 2
4+
* 2.从 step 开始,循环到 length
5+
* 3.将循环开始时的元素和比当前大 step 的元素进行比较
6+
* 4.发现逆序则进行交换
7+
*/
8+
9+
function shellSort(nums) {
10+
if (nums == null) {
11+
return;
12+
}
13+
let length = nums.length;
14+
// 控制步长
15+
for (let step = Math.floor(length / 2); step > 0; step = Math.floor(step / 2)) {
16+
for (let i = step; i < length; i++) {
17+
for (let j = i - step; j >= 0 && nums[j] > nums[j + step]; j -= step) {
18+
// 前面的数比后面的数大,进行交换
19+
swap(nums, j, j + step);
20+
}
21+
}
22+
}
23+
}
24+
25+
function swap(nums, i, j) {
26+
let temp = nums[i];
27+
nums[i] = nums[j];
28+
nums[j] = temp;
29+
}
30+
31+
function main() {
32+
let nums = [5, 1, 7, 3, 2, 4, 9, 6, 8];
33+
console.log("排序前: " + nums);
34+
shellSort(nums);
35+
console.log("排序后: " + nums);
36+
}
37+
38+
main();

0 commit comments

Comments
 (0)