1.描述
希尔排序(Shell Sort)是插入排序的一种算法,是对直接插入排序的一个优化,也称缩小增量排序。
希尔排序是基于直接插入排序的以下两点性质而提出的改进方法:
2.原理
希尔排序是将待排序的数组元素 按下标的一定增量(步长)分组 ,分成多个子序列,然后对各个子序列进行直接插入排序算法排序;然后依次缩减增量再进行排序,直到增量为1时,进行最后一次直接插入排序,排序结束。
每次切分,横向比较,直至步长为1。
3.时间复杂度
时间复杂度情况如下:(n指待排序序列长度)
1) 最好情况:序列是正序排列,在这种情况下,需要进行的比较操作需(n-1)次。后移赋值操作为0次。即O(n)
2) 最坏情况:O(nlog2n)。
3) 渐进时间复杂度(平均时间复杂度):O(nlog2n)
3.代码
//希尔排序
void shellSort(int array[], int length)
{
for (int step = length / 2; step > 0; step /= 2)
{
for (int index = step; index < length; index++)
{
int current = array[index];
for (int compare_index = index - step; compare_index >= 0; compare_index -= step)
{
if (current < array[compare_index])
{
array[compare_index + step] = array[compare_index];
array[compare_index] = current;
}
}
}
}