shell排序(C++实例)
来源:互联网 发布:windows更新过程中关闭 编辑:程序博客网 时间:2024/05/21 08:51
交换排序由于比较相邻元素,因此平均时间代码为Θ(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 0
- C实例---插入排序(Shell)
- shell排序(C++实例)
- C实例---快速排序(冒泡排序)
- c shell 脚本实例
- 插入排序----直接插入排序(C、C++、Python、Shell)
- Shell插入排序(c语言版)
- C 语言Shell 排序
- shell排序-c语言
- shell排序C实现
- C Tips: 排序算法:希尔排序(Shell sorting)
- shell排序法-改良的插入排序(C)
- 冒泡排序实例(C#)
- C语言程序----排序(直接插入排序,SHELL排序,冒泡排序,快速排序,简单选择排序,堆排序)
- C语言SHELL排序算法
- shell排序的c实现
- 插入排序、Shell排序和归并排序实例
- C / C++算法学习笔记(8)-SHELL排序
- C语言-冒泡排序-实例
- uva1401 - Remember the Word 前缀树DP
- linux 多线程类
- 拓胜第八十六天~第九十二天
- 线程池
- oracle提示TNS:无监听程序的解决办法
- shell排序(C++实例)
- QT OSG 浏览器插件 ,将OSG嵌入到IE中
- linq 基础
- “这圣域强者的领域当真可怕
- 引领世界企业通讯革命——AVAYA IP Office 云计划
- nginx正则表达式匹配文件名
- asp网站如何设置默认页_IIS 7.5 在 Windows Server(R) 2008 R2
- 3181867 常用软件下载
- “不但攻击快,力量更是强的离谱,而且竟然还有对时间的掌控?在那一刻不仅时间变慢,我的动作也是受到了不用程度的影响!若不是自己身处在领域中,恐怕还真来不及挡住这一招!”想到这里,科里不由得暗自心惊