快速排序 与 直接选择排序
2013-12-31 16:28
375 查看
/************************************************************************** * 题目:编写程序实现快速排序与直接选择排序相结合的排序算法。要求对输入 * 的序列,用PARTITION过程分割成小于10个记录为一组的子序列,然后 * 对每个子序列实施直接选择排序。 * 函数: * Swap: 交换两个参数的值 * Rand: 产生 begin至end之间的随机整数 * StraightSelectSort: 直接选择排序 * PARTITION: 分区 * QUICKSORT: 实现排序 * ***************************************************************************/ #include <iostream> #include <iomanip> #include <time.h> using namespace std; template < typename Type > void inline Swap (Type& a, Type& b) { Type temp = a; a = b; b = temp; } template < typename Type > Type inline Rand (Type begin, Type end) { Type value = rand()%(begin - end + 1) + begin; //value ~ [begin,end] return value; } template < typename Type > void StraightSelectSort (Type list[], int begin, int end) { int min; for(int i=begin; i <= end; ++i) { min = i; for(int j=i; j <= end; ++j) if(list[j] < list[min]) min = j; Swap<Type>(list[i],list[min]); } } template < typename Type > int PARTITION (Type list[], int begin, int end) { int temp = Rand (begin ,end); Swap(list[temp],list[end]); int i = begin - 1; int x = list[end]; for(int j = begin; j < end; ++j) // j: from begin to end-1 { if(list[j] <= x) { ++i; Swap(list[i], list[j]); } } Swap(list[i+1], list[end]); return ++i; } template < typename Type > void QUICKSORT ( Type list[], int begin, int end) { if(begin >= end) return; else if ( end - begin < 10 ) StraightSelectSort (list, begin, end); else { int q = PARTITION (list, begin, end); QUICKSORT (list, begin, q-1); QUICKSORT (list, q, end); } } //测试 int main() { srand(time(0)); int x[100]; for(int i=0;i<100;++i) x[i] = Rand(0, 1000); cout << "随机生成的原始数据 :"; for(int i=0;i<100;++i) { if(0 == i%10) cout<<endl; cout << setw(5) << x[i]; } QUICKSORT (x, 0, 99); cout << endl << endl << "排序后的数据:"; for(int i=0;i<100;++i) { if (0 == i%10) cout<<endl; cout << setw(5) << x[i]; } return 0; }
相关文章推荐
- Http协议简单学习笔记
- 学习python中的一些问题--centos下django连接mysql配置
- 网站被写入恶意代码的主要原因及防范策略
- 2013资料整理-IOS音频格式AMR和WAV互转
- HBase0.96.x开发使用(三)-- java客户端使用
- 螺旋藻2
- linux下面tomcat域名配置
- DBA应该掌握的SQL语句
- oracle自动导出Function、procedure等存储过程;
- AnyChat platform Core SDK V4.9 preview版本发布啦
- t_sql语句得到表中所有信息
- “添加到收藏夹”功能(share)
- android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context re
- 块设备驱动3--sd卡驱动2(linux-3.2.36的host.h分析)
- Linux C编程——more命令的实现
- JBPM4.4应用开发
- cocos2d-x之CCGUI设计与实现(1)序言
- Kernel中uart接口的bluetooth driver初始化分析
- Kernel中Hid和Bnep的初始化
- oracle中的NVL,NVL2,NULLIF,COALESCE几个通用函数