shell排序(C++实例)
2014-03-17 09:14
405 查看
交换排序由于比较相邻元素,因此平均时间代码为Θ(n2)。
shell排序也称为缩小增量排序。利用插入排序的最佳时间特性,将待排序序列分成若干子序列,然后分别对子序列排序,最后将子序列组合起来。
如下图所示:
算法的实现:
结果输出:
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)。
参考:
《数据结构与算法分析》
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)。
参考:
《数据结构与算法分析》
相关文章推荐
- 用两个栈模拟队列实例(C++)
- c++中的引用的使用原理和使用实例 (2)
- Linux下C++的hello world实例
- c++之多文件编写实例
- C++普通函数指针与成员函数指针实例解析
- C++的单实例方法
- VS2010 Win7 64位 C++ MFC DataGrid绑定实例
- C++串口编程实例
- 【转】C++易混知识点5:实例讲解Public Protected Private作用域,继承的区别和用意
- 删除特定位置前面的字符串c++代码实例及运行结果
- C++模拟键盘按键的实例
- 大话设计模式--享元模式 Flyweight -- C++实现实例
- 交通标识牌识别c++代码实例及运行结果
- C++中引用(&)的用法和应用实例
- 23种设计模式C++实例之解释器模式
- C++时间戳转化操作实例分析【涉及GMT与CST时区转化】
- 用C++编写的SOCKET服务端与客户端代码实例
- C++面向对象类的实例题目八
- C++面向对象类的实例题目十
- C++面向对象类的实例题目十一