希尔排序
笔记
将数组分成若干个子序列,一开始是 len/2,然后不断除以2,直到1为止,对每个子序列进行插入排序。
注意
不稳定排序
#include<bits/stdc++.h>
using namespace std;
/**
* 希尔排序
* */
// 通过交换方式插入
void shell_sort_swap(int a[], int len) {
for(int gap = len/2; gap > 0; gap /= 2) {
for(int i = gap; i < len; i++) {
int pre = i;
while(pre-gap >= 0 && a[pre] < a[pre-gap]) {
swap(a[pre], a[pre-gap]);
pre -= gap;
}
}
}
}
// 通过移动方式插入
void shell_sort_move(int a[], int len) {
for(int gap = len/2; gap > 0; gap /= 2) {
for(int i = gap; i < len; i++) {
int pre = i;
int cur = a[i];
while(pre-gap >= 0 && cur < a[pre-gap]) {
a[pre] = a[pre-gap];
pre -= gap;
}
a[pre] = cur;
}
}
}
int main() {
int a[] = {9, 3, 1, 4, 2, 7, 8, 6, 5};
int len = sizeof(a)/sizeof(a[0]);
shell_sort_swap(a, len);
for(int i = 0; i < len; i++) {
printf("%d%c", a[i], " \n"[i==len-1]);
}
return 0;
}
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
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
# 参考链接
编辑 (opens new window)
上次更新: 2025/05/21, 06:42:57