一、希尔排序简介
希尔排序(Shell Sort)是插入排序的一种,它是针对直接插入排序算法的改进。该方法又称缩小增量排序,因DL.Shell于1959年提出而得名。
希尔排序实质上是一种分组插入方法。它的基本思想是:对于n个待排序的数列,取一个小于n的整数gap(gap被称为步长)将待排序元素分成若干个组子序列,所有距离为gap的倍数的记录放在同一个组中;然后,对各组内的元素进行直接插入排序。 这一趟排序完成之后,每一个组的元素都是有序的。然后减小gap的值,并重复执行上述的分组和排序。重复这样的操作,当gap=1时,整个数列就是有序的。
二、希尔排序的时间复杂度和稳定性
希尔排序时间复杂度
希尔排序的时间复杂度与增量(即,步长gap)的选取有关。例如,当增量为1时,希尔排序退化成了插入排序,此时的时间复杂度为O(N²),而Hibbard增量的希尔排序的时间复杂度为O(N3/2)。
希尔排序稳定性
希尔排序是不稳定的算法,它满足稳定算法的定义。对于相同的两个数,可能由于分在不同的组中而导致它们的顺序发生变化。
算法稳定性 -- 假设在数列中存在a[i]=a[j],若在排序之前,a[i]在a[j]前面;并且排序之后,a[i]仍然在a[j]前面。则这个排序算法是稳定的!
三、C++代码实现
1.实现代码
//Sort.h
#include<vector>
using namespace std;
template <typename T>
bool lessthan(const T &a, const T &b)
{
return a < b;
}
template <typename T>
void exch(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T>
void show(const vector<T> &a)
{
for (auto tmp : a)
cout << tmp<<" ";
}
template <typename T>
bool isSorted(const vector<T> &a)
{
int cnt = a.size();
for (int i = 0; i < cnt-1; i++)
{
if (a[i] > a[i + 1])
return false;
}
return true;
}
template <typename T>
void read(vector<T> &v, const string s)
{
ifstream data(s); //待读取文件的目录
string line;
while (getline(data, line)) {
stringstream ss; //输入流
ss << line; //向流中传值
if (!ss.eof()) {
int temp;
while (ss >> temp) //提取int数据
v.push_back(temp); //保存到vector
}
}
}
template <typename T>
void ShellSort(vector<T> &a)
{
int cnt = a.size();
int h = 1;
while (h < cnt / 3)
h = h * 4 +1;
while (h >= 1)
{
for (int i = h; i < cnt; i++)
{
for (int j = i; j >=h && lessthan(a[j], a[j - h]); j=j-h)
{
exch(a[j], a[j - h]);
}
}
h = h / 4;
}
}
2.用例代码
#include<iostream>
#include<fstream>
#include<sstream>
#include<algorithm>
#include<string>
#include<vector>
#include<time.h>
#include"Sort.h"
using namespace std;
int main()
{
clock_t start, finish;
double time=0; // CLOCKS_PER_SEC;
vector<int> vec;
read(vec, "16Kints.txt");
cout << vec.size()<<endl;
for (int i = 0; i < 10; i++)
{
start = clock(); //测试程序段花费的时间
ShellSort(vec);
//InsertionSort(vec);
//SelectionSort(vec);
//MergeSort(vec);
QuickSort(vec);
finish = clock();
time += (double)(finish - start);
cout << isSorted(vec) << endl;
random_shuffle(vec.begin(), vec.end());
}
cout << "运行时间是" << time<<endl;
//show(vec);
system("pause");
}