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

来源:互联网 发布:红颜知已歌曲 编辑:程序博客网 时间:2024/05/17 21:45

名字来源

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

缩小增量排序

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

源码

template <class T>//shell_sortint 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)

稳定性

不稳定

0 0
原创粉丝点击