《C算法》读书笔记8:shell sort

希尔排序 shellsort 是变种的插入排序 insertsort 。在面对部分有序数据的时候,插入排序的效率接近 O(n) ,因为插入排序的交换效率直接取决于逆序数对的数量。
插入排序的缺点是两次相邻的外循环不能交换太远的项 Item ,必须依次从左到右进行,假如运气不好,最小键所在项在最右边,就得需要N步才能结束。

void insert_sort2(int *a, int l, int r)
{
    int step = 0;
iter1:
    for(int i = l + 1; i <= r; ++ i)
    {
        int j = i;
        int v = a[i];
        while(j >= l + 1 && LT(v, a[j - 1]))
        {
            a[j] = a[j - 1];
            -- j;
            ++ step;
        }
        a[j] = v;
    }
    printf("insert sort step: %d\n", step);
}

希尔排序的改进是在外循环iter1外面再增加偏移量h,每次重排后得到如下性质:每隔h取一项,使得该新数组为有序。依次减少偏移量,到最后一次使偏移量为1。因前言所述插入排序的性质,每次排序都可以用插入排序完成。
值得重视的是偏移量的选取方式。在对一组随机生成的N=10000的数据统计后,发现以下几种偏移量较为佳。
(1):4095 2047 1023 511 255 127 63 31 15 7 3 1 hn=hn+12+1
(2):3280 1093 364 121 40 13 4 1 hn=hn+13+1

而下面的方式效果不佳:
(1):4096 2048 1024 512 256 128 64 32 16 8 4 2 1 hn=hn+12

void shell_sort(int *a, int l, int r)
{
    int h;
    for(h = 1; h <= (r - l) / 4; h = 2 * h);
    int step = 0;
    for(; h; h /= 2)
    {
        printf("%d ", h);
        for(int i = l + h; i <= r; ++ i)
        {
            int j = i;
            int v = a[i];
            while(j >= l + h && LT(v, a[j - h]))
            {
                a[j] = a[j - h];
                j -= h;
                ++ step;
            }
            a[j] = v;
        }
    }
    printf("\nshell sort step %d\n", step);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值