插入排序之shell排序分析及源码演示

版权声明:本人才疏学浅,欢迎大家批评指正,互相讨论学习。 https://blog.csdn.net/scuyxi/article/details/70560557

名字来源

shell排序属于插入排序,因DL.Shell于1959年提出而得名。

缩小增量排序

shell排序利用了直接插入排序在原序列比较有序的情况下,排序速度较快的原理。通过多次排序,每次缩小增量,序列一次比一次有序,当增量为1时,序列已经有序。

源码

template <class T>

//shell_sort
int sort(T *t, int n)
{
    int d = n / 2;
    int comp_times = 0;
    while(d >= 1)
    {
        for(int i=0; i<d; i+=1)
        {
            for(int k=i+d; k<n; k+=d)
            {
                T current = t[k];
                int m=k-d;
                for(; m>=i; m-=d)
                {
                    comp_times++;
                    if(t[m] > current)
                    {
                        t[m+d] = t[m];
                    }
                    else
                    {
                        break;
                    }
                }
                t[m+d] = current;
            }
        }
        d /= 2;
    }
    return comp_times;
}

执行结果:
这里写图片描述

时间复杂度

与增量大小有关:
平均为??(不确定)

o(nlog2n)

空间复杂度

o(1)

稳定性

不稳定

猜你喜欢

转载自blog.csdn.net/scuyxi/article/details/70560557