shell排序(C++实例)

17 篇文章 2 订阅

交换排序由于比较相邻元素,因此平均时间代码为Θ(n2)。

shell排序也称为缩小增量排序。利用插入排序的最佳时间特性,将待排序序列分成若干子序列,然后分别对子序列排序,最后将子序列组合起来。

如下图所示:


算法的实现:

#include "stdio.h"

const int gi_incre = 2;

template< class Elem >
int inssort2( Elem list[], int n, int incre )
{
    int i, j;
    Elem elem_tmp;
    for ( i = incre; i < n; i += incre )
    {
        for ( j = i; ( j >= incre ) && ( list[j] < list[j - incre] ); j -= incre )
        {
            // swap Elem[j] and Elem[j - incre]
            elem_tmp = list[j];
            list[j] = list[j - incre];
            list[j - incre] = elem_tmp;
        }
    }
    return 0;
}   
    
    
template< class Elem >
int shellsort( Elem list[], int n )
{
    int i, j;
    for ( i = n/gi_incre; i > gi_incre; i /= gi_incre )
    {
        printf( "i: %d\n", i );
        for ( j = 0; j < i; j++ )
        {
            inssort2< Elem >( &list[j], n - j, i );
        }
    }
    inssort2< Elem >( list, n, 1 );
    return 0;
}

int main()
{
    int p_srcarr[] = {59, 20, 17, 13, 28, 14, 23, 83, 36, 98, 11, 70, 65, 41, 42, 15};
    const int i_len = 16;

    printf( "%s", "before shellsort\n" );
    int i_index = 0;
    for( i_index = 0; i_index < i_len; i_index ++ )
    {
        printf( "%4d", p_srcarr[i_index] );
    }
    printf( "%s", "\n" );

    shellsort( p_srcarr, i_len );

    printf( "%s", "after shellsort\n" );
    for( i_index = 0; i_index < i_len; i_index ++ )
    {
        printf( "%4d", p_srcarr[i_index] );
    }
    printf( "%s", "\n" );
    return 0;
}

结果输出:

before shellsort
  59  20  17  13  28  14  23  83  36  98  11  70  65  41  42  15
i: 8
i: 4
after shellsort
  11  13  14  15  17  20  23  28  36  41  42  59  65  70  83  98

不对增量为gi_incre(本例中为2)的情况再进行一次排序?

个人理解,是因为插入排序的最好时间代价为θ(n),对于基本有序的数据采用插入排序的效率很高。

选择适当的增量序列,可以使用shell排序比其它排序更有效。

一般来说,增量每次除以2时,并没有多大效果。增量每次除以3时,效果最好。

分析shell的时间代价是很困难的,因此必须不加证明地承认,增量每次除以3时,shell排序的平均运行时间为Θ(n1.5)。


参考:

《数据结构与算法分析》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值