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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* @Author: CrayonXiaoxin
* @Date: 2023-12-13 20:31:58
* @LastEditors: Do not edit
* @LastEditTime: 2023-12-20 19:37:55
* @FilePath: \c++\code\C.cpp
*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
const int maxn = 2e5+10;
int a[maxn];
void solve()
{
int n;
cin >> n;
for (int i = 0; i < n;++i)
cin >> a[i];
int gap = n;
while(gap > 1)
{
gap /= 2;
for (int i = 0; i < n - gap;++i)
{
int end = i;
int tem = a[end + gap];
while(end>=0)
{
if(tem>a[end])
{
a[end + gap] = a[end];
end -= gap;
}
else
{
break;
}
}
a[end + gap] = tem;
}
for (int i = 0; i < n-1;++i)
cout << a[i] << " ";
cout << a[n - 1];
cout << "\n";
}



}

int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while(t--)
{
solve();
cout << "\n";
}
return 0;
}