希尔排序
说明:
在复习数据结构,对希尔排序做了一下小结。主要是写了一个模板,文章没有对shell排序算法进行详细分析。
1. 思路
实际上还是插入排序,但是shell排序对待排记录序列先作“宏观”调整,再作“微观”调整。
- 确定增量序列(间隔序列): 选择一个增量序列,通常使用 Knuth 序列(保证步长相对质数),该序列在排序中不断减小,直到最后一步的增量为 1。
// 使用 Knuth 序列确定增量(间隔)
int h = 1;
while (h < n / 3)
h = 3 * h + 1;
- 外层循环: 对于每个增量,执行一轮插入排序。增量决定了每一轮的步长。
while (h >= 1)
- 内层插入排序: 对于当前增量,使用插入排序算法。插入排序将数据分为有序和无序两个部分。从第一个增量开始,对每个子序列进行插入排序。
for (int i = h; i < n; ++i)
for (int j = i; j >= h && arr[j] < arr[j - h]; j -= h)
swap(arr[j], arr[j - h]);
- 缩小增量: 逐步缩小增量,重复步骤 ,直到增量为 1。
h /= 3
下面为代码运行过程,python画的,有点丑,但是将就吧,实在没时间弄那华丽花哨的:
2. 算法样例
程序运行保证正确:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void shellSort(vector<T>& arr) {
int n = arr.size();
// 使用 Knuth 序列确定增量(间隔)
int h = 1;
while (h < n / 3)
h = 3 * h + 1;
// 开始 Shell 排序
while (h >= 1) {
// 插入排序
for (int i = h; i < n; ++i)
for (int j = i; j >= h && arr[j] < arr[j - h]; j -= h)
swap(arr[j], arr[j - h]);
// 减小增量
h /= 3;
}
}
int main() {
// 示例用法,整数类型
vector<int> intData = {12, 5, 23, 1, 67, 43, 8, 19};
cout << "Original array (int): ";
for (int num : intData) {
cout << num << " ";
}
cout << endl;
shellSort(intData);
cout << "Sorted array (int): ";
for (int num : intData) {
cout << num << " ";
}
cout << endl;
return 0;
}
3. 算法复杂度分析
- 最坏情况下:
- SHELL 排序的时间复杂度依赖于使用的增量序列。最坏情况下,当使用一些常见的增量序列(如 Knuth 序列)时,时间复杂度为 O ( n 3 / 2 ) O(n^{3/2}) O(n3/2)。
- 平均情况下:
- 平均时间复杂度是一个开放问题,没有确定的解析性质。在实际情况中,SHELL 排序通常表现得比 O ( n 2 ) O(n^2) O(n2) 的排序算法好,但不如 O ( n log n ) O(n \log n) O(nlogn)的算法。