博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++实现快速排序
阅读量:6936 次
发布时间:2019-06-27

本文共 1945 字,大约阅读时间需要 6 分钟。

1 //============================================================================ 2 // Name        : C++Basic.cpp 3 // Author      : Laughing 4 // Version     : 5 // Copyright   : All Right Reserved 6 // Description : 快速排序:采用分治法 7 //============================================================================ 8  9 #include 
10 #include
11 #include
12 using namespace std;13 /**14 *快速排序:采用分治法15 */16 int partition(int array[], int start, int end) { //返回基准的下标17 if (array == NULL) {18 cout << "数组为空" << endl;19 throw new exception();20 }21 int base = rand() % (end - start + 1); //若基准为随机元素,则递归次数不定,即时间复杂度有差别!★22 // int base = 0;//若基准为数组第一个元素或某个固定元素,则递归次数固定。23 cout << "基准为:" << base << endl;24 int basic = array[base];//basic为基准25 while (start < end) {26 while (start < end && array[end] > basic) {27 end--;28 }29 if (start < end) { //★30 array[base] = array[end];31 base = end; //改变基准指向的下标32 }33 while (start < end && array[start] < basic) {34 start++;35 }36 if (start < end) { //★37 array[base] = array[start];38 base = start; //改变基准指向的下标39 }40 }41 array[base] = basic;42 return base;43 }44 void QuickSort(int array[], int start, int end) {45 if (start < end) {46 int base = partition(array, start, end);47 QuickSort(array, 0, base - 1);48 QuickSort(array, base + 1, end);49 }50 }51 int main() {52 // srand((int)time(0));//初始化随机种子:若不初始化,每次递归的随机种子不会变化,递归次数固定。53 int array[] = { 4, 3, 2, 1, 9, 7, 5, 8, 6 };54 int size = sizeof(array) / sizeof(*array); //求数组长度55 QuickSort(array, 0, size - 1);56 for (int i = 0; i < size; i++) {57 cout << array[i] << endl;58 }59 return 0;60 }

 

转载于:https://www.cnblogs.com/Laughing-Lz/p/5509927.html

你可能感兴趣的文章
jsp 传值jsp 数据库 乱码解决的攻略 全套
查看>>
SpringCloud的服务注册中心(二)注册中心服务端和两个微服务应用客户端
查看>>
javaScript 设计模式之中介者模式示例
查看>>
classes目录中没有class文件的一个原因
查看>>
微信公众平台开发 一 账号类别与申请
查看>>
取指定的字符串,字符串里面有汉字和字母
查看>>
华为招聘机试整理10:实现字符串中子字符串的替换
查看>>
VMware虚拟机上安装linux和克隆
查看>>
Python的open函数
查看>>
IDEA在debug时修改变量值
查看>>
Dell poweredge r210进BIOS改动磁盘控制器(SATA Controller)接口模式
查看>>
Go 1.5keyword搜索文件夹、文件、文件内容_修复一个小BUG
查看>>
20160205.CCPP体系具体解释(0015天)
查看>>
匈牙利算法解决二分图匹配
查看>>
.NET Core 2.0 单元测试中初识 IOptionsMonitor<T>
查看>>
关于内存中栈和堆的区别(非数据结构中的堆和栈,区别)
查看>>
redhat6.7在线安装postgresql9
查看>>
Advanced Installer 打包后,安装包在WIN10下重启后再次运行安装的解决办法
查看>>
js实现手机页面定位
查看>>
第三方Android 模拟器流畅速度快,适合开发人员
查看>>