第十六周项目1-验证算法插入排序之希尔排序
2015-12-14 17:08
357 查看
希尔排序
运算结果:
排序中输出每一趟的中间结果:
#include <stdio.h> #define MaxSize 20 typedef int KeyType; //定义关键字类型 typedef char InfoType[10]; typedef struct //记录类型 { KeyType key; //关键字项 InfoType data; //其他数据项,类型为InfoType } RecType; //排序的记录类型定义 void ShellSort(RecType R[],int n) //希尔排序算法 { int i,j,gap; RecType tmp; gap=n/2; //增量置初值 while (gap>0) { for (i=gap; i<n; i++) //对所有相隔gap位置的所有元素组进行排序 { tmp=R[i]; j=i-gap; while (j>=0 && tmp.key<R[j].key)//对相隔gap位置的元素组进行排序 { R[j+gap]=R[j]; j=j-gap; } R[j+gap]=tmp; j=j-gap; } gap=gap/2; //减小增量 } } int main() { int i,n=11; RecType R[MaxSize]; KeyType a[]= {16,25,12,30,47,11,23,36,9,18,31}; for (i=0; i<n; i++) R[i].key=a[i]; printf("排序前:"); for (i=0; i<n; i++) printf("%d ",R[i].key); printf("\n"); ShellSort(R,n); printf("排序后:"); for (i=0; i<n; i++) printf("%d ",R[i].key); printf("\n"); return 0; }
运算结果:
排序中输出每一趟的中间结果:
#include <stdio.h> #define MaxSize 20 typedef int KeyType; //定义关键字类型 typedef char InfoType[10]; typedef struct //记录类型 { KeyType key; //关键字项 InfoType data; //其他数据项,类型为InfoType } RecType; //排序的记录类型定义 void ShellSort(RecType R[],int n) //希尔排序算法 { int i,j,gap,k; RecType tmp; gap=n/2; //增量置初值 while (gap>0) { for (i=gap; i<n; i++) //对所有相隔gap位置的所有元素组进行排序 { tmp=R[i]; j=i-gap; while (j>=0 && tmp.key<R[j].key)//对相隔gap位置的元素组进行排序 { R[j+gap]=R[j]; j=j-gap; } R[j+gap]=tmp; j=j-gap; } printf("gap=%d:",gap); for (k=0; k<n; k++) printf("%d ",R[k].key); printf("\n"); gap=gap/2; //减小增量 } } int main() { int i,n=11; RecType R[MaxSize]; KeyType a[]= {16,25,12,30,47,11,23,36,9,18,31}; for (i=0; i<n; i++) R[i].key=a[i]; printf("排序前:"); for (i=0; i<n; i++) printf("%d ",R[i].key); printf("\n"); ShellSort(R,n); printf("排序后:"); for (i=0; i<n; i++) printf("%d ",R[i].key); printf("\n"); return 0; }
相关文章推荐
- msyql 批量 更新 与 批量 更新多条记录不同的值
- 第十四周项目1-(3) 验证分块查找算法
- 第16周、项目4—英文单词的基数排序
- 第十六周 项目1-验证算法(5)
- 第十六周上机实践—项目1(4)—验证算法 冒泡排序 直接选择排序
- ofbiz框架入门例子详解-------分页篇
- hibernate使用懒加载时,mvc转json时因为session已经关闭报错
- 关于vs2012+caffe配置中出现的"常量中的字符太多"错误的解决办法
- 跨浏览器的事件侦听器和事件对象
- LeetCode - Regular Expression Matching
- 第十六周——【项目3 - 归并排序算法的改进】
- 第16周 项目1-直接选择排序
- 第十六周--英文单词的基数排序
- 第十五周项目二:用哈希法组织关键字
- 第十六周项目1-基数排序
- HTTP头部详解
- MPAndroidChart 教程:与图表进行手势交互 Interaction with the Chart(二)
- Androidying应用之多线程机制Handler
- 字符串结尾字符的含义
- shareSDK使用心得