您的位置:首页 > 运维架构 > Shell

shell排序(C++实例)

2014-03-17 09:14 405 查看
交换排序由于比较相邻元素,因此平均时间代码为Θ(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)。

参考:

《数据结构与算法分析》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: