第十六周--验证算法(快速排序)
2015-12-14 16:24
411 查看
/* *Copyright (c) 2015 烟台大学计算机与控制工程学院 *All right reserved. *标题:数据结构实践——验证算法 快速排序 *作者:杨珺 *date:2015年12月14日 *版本:V1.0.1 *操作系统:XP *运行环境:VC6.0 *问题描述:用序列{57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}作为测试数据, 运行并本周视频中所讲过的算法对应 程序,观察运行结果并深刻领会算法的思路和实现方法 */
以第一个元素作为基准:
#include <stdio.h> #define MaxSize 20 typedef int KeyType; //定义关键字类型 typedef char InfoType[10]; typedef struct //记录类型 { KeyType key; //关键字项 InfoType data; //其他数据项,类型为InfoType } RecType; //排序的记录类型定义 void QuickSort(RecType R[],int s,int t) //对R[s]至R[t]的元素进行快速排序 { int i=s,j=t; RecType tmp; if (s<t) //区间内至少存在两个元素的情况 { tmp=R[s]; //用区间的第1个记录作为基准 while (i!=j) //从区间两端交替向中间扫描,直至i=j为止 { while (j>i && R[j].key>=tmp.key) j--; //从右向左扫描,找第1个小于tmp.key的R[j] R[i]=R[j]; //找到这样的R[j],R[i]"R[j]交换 while (i<j && R[i].key<=tmp.key) i++; //从左向右扫描,找第1个大于tmp.key的记录R[i] R[j]=R[i]; //找到这样的R[i],R[i]"R[j]交换 } R[i]=tmp; QuickSort(R,s,i-1); //对左区间递归排序 QuickSort(R,i+1,t); //对右区间递归排序 } } int main() { int i,n=10; RecType R[MaxSize]; KeyType a[]= {57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}; 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"); QuickSort(R,0,n-1); 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 QuickSort1(RecType R[],int s,int t) //对R[s]至R[t]的元素进行快速排序 { int i=s,j=t; KeyType pivot; RecType tmp; pivot = R[(s+t)/2].key; //用区间的中间位置的元素作为关键字 if (s<t) //区间内至少存在两个元素的情况 { while (i!=j) //从区间两端交替向中间扫描,直至i=j为止 { while (j>i && R[j].key>pivot) j--; //从右向左扫描,找第1个小于基准的R[j] while (i<j && R[i].key<pivot) i++; //从左向右扫描,找第1个大于基准记录R[i] if(i<j) //将前后的两个失序元素进行交换 { tmp=R[i]; R[i]=R[j]; R[j]=tmp; } } QuickSort1(R,s,i-1); //对左区间递归排序 QuickSort1(R,j+1,t); //对右区间递归排序 } } int main() { int i,n=10; RecType R[MaxSize]; KeyType a[]= {57, 40, 38, 11, 13, 34, 48, 75, 6, 19, 9, 7}; 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"); QuickSort1(R,0,n-1); printf("排序后:"); for (i=0; i<n; i++) printf("%d ",R[i].key); printf("\n"); return 0; }
运行结果:
相关文章推荐
- 大数据全栈式开发语言——Python
- springMVC.xml与springContext.xml关系与区别
- 第15周项目3B-树的基本操作
- PHP中单引号和双引号的区别
- IOS 蓝牙4.0(BLE 协议) 初窥
- python基础教程共60课-第40课用文件保存游戏2
- Formal sys-Pradicate semantic
- 剑指offer系列之四十五:左旋转字符串
- 高效加载Bitmap
- 自动化测试模型总结
- sql server case when 判断为空
- git 怎么看某个commit 修改的代码
- 16周 - 项目一-验证算法-直接插入排序
- 第十六周上机实践项目1 - 验证算法(直接选择排序)
- 测试开发Python培训:模拟登录新浪微博-技术篇 2
- PHP实现四种基本排序算法 得多消化消化
- C++学习笔记10-面向对象
- (第十五周项目3)B-树的基本操作(选看)
- 测试开发Python培训:模拟登录新浪微博-技术篇
- 解决Android平台中应用程序OOM异常的方法