直接插入排序与希尔排序
2015-07-05 16:42
295 查看
代码是何其的相似啊!!
/* Name: InsertSort Copyright: Author: huowolf Date: 05/07/15 16:18 Description: 直接插入排序的实现 */ #include <iostream> using namespace std; int arr[]={-1,48,62,35,77,55,14,35,98}; void InsertSort(int a[],int length); void Output(int a[],int length); int main() { InsertSort(arr,8); Output(arr,8); return 0; } void InsertSort(int a[],int length) { int i,j; for(i=2;i<=length;i++) { if(a[i]<a[i-1]) { a[0] = a[i]; //拷贝为哨兵 for(j=i-1;a[0]<a[j];j--) a[j+1]=a[j]; //记录后移,寻找插入位置 a[j+1] = a[0]; //插入 } } } void Output(int a[],int length) { for(int i=1;i<=length;i++) cout<<a[i]<<" "; }
/* Name: ShellSort Copyright: Author: huowolf Date: 05/07/15 16:18 Description: 希尔排序的实现 */ #include <iostream> using namespace std; int arr[]={-1,48,62,35,77,55,14,35,98}; void ShellSort(int a[],int length); void Output(int a[],int length); int main() { ShellSort(arr,8); Output(arr,8); return 0; } void ShellSort(int a[],int length) { int i,j; int d = length; //将增量初始化为表长 do{ d = d/3+1; //增量序列 (一种比较经典的增量取法,但并没有给出最优性证明) for(i=d+1;i<=length;i++) { if(a[i]<a[i-d]) //在同一子序列中相邻的前后元素 { a[0] = a[i]; for(j=i-d;j>0 && a[0]<a[j];j-=d) //记录后移,寻找插入位置 a[j+d] = a[j]; a[j+d] = a[0]; } } }while(d>1);//增量为1,停止循环 } void Output(int a[],int length) { for(int i=1;i<=length;i++) cout<<a[i]<<" "; }
相关文章推荐
- 设计一个算法,求非空二叉树b的宽度(即具有节点最多的那一层的节点个数)
- 权限设计解决方案
- Ehcache缓存配置
- Oracle ->> 层级查询语句(hierarchical query)connect by
- PHP常用功能模块
- 《编程实用算法实现整理》系列技术文章整理收藏
- 解决Win7 64位玩游戏不兼容的问题
- 关于使用python logging模块的几点总结
- org.apache.hadoop.security.AccessControlException: Permission denied: 权限错误
- 非智力因素与成功
- 业务规划以及如何使用云计算平台?
- CentOS6.x 升级 CentOS7.1
- Android调用手机自带图库选择图片
- 动画和核心动画为基础的导航
- poj 3274 Gold Balanced Lineup Hash
- codeforces 394C Dominoes
- 3DX
- 《编程常见数据结构知识》系列技术文章整理收藏
- 线段树讲解(数据结构、C++)
- 面试题37:两个链表的第一个公共结点