当前位置:网站首页>快速排序的非递归写法
快速排序的非递归写法
2022-06-11 21:36:00 【爱学代码的学生】
学习了快速排序的递归算法,我们可能会感叹递归真是一个好东西,但是在不同的情况下,我们需要考虑很多东西,如果在大数据的影响下使用递归发生了栈溢出,那我们这时候就应该考虑使用非递归来实现快速排序。
代码实现如下:
//非递归实现快速排序
void QuickSort3(int*a,int left,int right){
ST s;
InitStack(&s);
StackPush(&s,left);
StackPush(&s,right);
while(!StackEmpty(s)){
int end=StackGet(s);
StackPop(&s);
int start=StackGet(s);
StackPop(&s);
int pivot=Partition1(a,start,end);
if(start<pivot-1){
StackPush(&s,start);
StackPush(&s,pivot-1);
}
if(pivot+1<end){
StackPush(&s,pivot+1);
StackPush(&s,end);
}
}
StackDestory(&s);
}这里我们使用了栈来帮助我们完成类似递归的效果。
实现步骤:
1. 传入了区间left,right
2. 取出left,right,并且得到基准数的下标
3. 判断区间[left,pivot-1] [pivot+1,end]是否存在,若存在则存入栈
4. 重复上述操作,直到栈中没有元素
记得使用完了栈要进行销毁。
边栏推荐
- apache 本地多端口配置
- Jenkins+allure integrated report construction
- Bipartite King
- flutter系列之:flutter中常用的container layout详解
- Leetcode-110-balanced binary tree
- EndnoteX9簡介及基本教程使用說明
- Codeforces Round #739 (Div. 3)解题报告
- 行而不辍,未来可期|云扩科技入选上海市专精特新企业
- Iros 2021 | new idea of laser vision fusion? Lidar intensity diagram +vpr
- Leetcode 797. All possible paths
猜你喜欢

servlet获取表单数据

Database daily question --- day 9: salesperson

flutter系列之:flutter中常用的container layout详解
![[Part 15] use and basic principle of forkjoinpool [key]](/img/36/e21b16ec92d444149bc793f340f9f3.jpg)
[Part 15] use and basic principle of forkjoinpool [key]

LeetCode-76-最小覆盖子串

A collection of commonly used open source data sets for face recognition

如何使用事物码 SAT 查找某个 SAPGUI 屏幕字段对应的后台存储数据库表的名称

zypper命令使用示例

JVM | virtual machine stack (local variable table; operand stack; dynamic link; method binding mechanism; method call; method return address)
![BZOJ3189 : [Coci2011] Slika](/img/46/c3aa54b7b3e7dfba75a7413dfd5b68.png)
BZOJ3189 : [Coci2011] Slika
随机推荐
关于斜率优化
Experiment 10 Bezier curve generation - experiment improvement - control point generation of B-spline curve
Leetcode-98- validate binary search tree
Release of version 5.6 of rainbow, add multiple installation methods, and optimize the topology operation experience
In the future, cloud expansion technology is expected to be selected as a specialized, special and new enterprise in Shanghai
189. 轮转数组
Apache local multi port configuration
Only 38 years old! Zhou Chuan, a researcher of the Chinese Academy of Sciences, died unfortunately. Rao Yi sent a document to mourn: he guided me when he was still my student
zypper命令使用示例
Jenkins+allure integrated report construction
LeetCode-322-零钱兑换
Realize the same length of tablayout subscript and text, and change the selected font size
LabVIEW Arduino electronic weighing system (project Part-1)
2021 Niuke multi school 5 double strings
Relatively perfect singleton mode
select _ Lazy loading
LeetCode-129-求根节点到叶节点数字之和
类和对象(1)
Using the sap ui5 cli command line tool to build and run SAP ui5 applications
LeetCode-32-最长有效括号