快排非递归实现
2015-08-07 00:42
375 查看
int partition(int* arr, int low, int high)
{
int pivot = arr[low];
while(low < high)
{
while(low < high && arr[high] >= pivot)
high--;
arr[low] = arr[high];
while(low < high && arr[low] <= pivot)
low--;
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
void non_recursive_qsort(int* arr, int low, int high)
{
stack<int> s;
int pivot;
if(low < high)
return ;
pivot = partition(arr, low, high)
if(low < pivot - 1)
{
s.push(low);
s.push(pivot - 1);
}
if(high > pivot + 1)
{
s.push(high);
s.push(pivot + 1);
}
//其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作
//如果pivot的左段或右段已经少于两个元素了,则无需再对这个子段partition了
while(!s.empty())
{
high = s.top();
s.pop();
low = s.top();
s.pop();
pivot = partition(arr, low, high)
if(low < pivot - 1)
{
s.push(low);
s.push(pivot - 1);
}
if(high > pivot + 1)
{
s.push(high);
s.push(pivot + 1);
}
}
}
{
int pivot = arr[low];
while(low < high)
{
while(low < high && arr[high] >= pivot)
high--;
arr[low] = arr[high];
while(low < high && arr[low] <= pivot)
low--;
arr[high] = arr[low];
}
arr[low] = pivot;
return low;
}
void non_recursive_qsort(int* arr, int low, int high)
{
stack<int> s;
int pivot;
if(low < high)
return ;
pivot = partition(arr, low, high)
if(low < pivot - 1)
{
s.push(low);
s.push(pivot - 1);
}
if(high > pivot + 1)
{
s.push(high);
s.push(pivot + 1);
}
//其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作
//如果pivot的左段或右段已经少于两个元素了,则无需再对这个子段partition了
while(!s.empty())
{
high = s.top();
s.pop();
low = s.top();
s.pop();
pivot = partition(arr, low, high)
if(low < pivot - 1)
{
s.push(low);
s.push(pivot - 1);
}
if(high > pivot + 1)
{
s.push(high);
s.push(pivot + 1);
}
}
}
相关文章推荐
- Button鼠标箭头变手势
- jQuery+css+div一些值得注意的常用语句
- VC++ 标准C++中的string类的用法总结
- 利用外网主机穿透本地网络防火墙
- eclipseMars4.5+maven3+jetty8的简单使用
- NSMutableAttributedString可变字符串使用
- 安装Windows后恢复CentOS 7 grub2启动项
- DIV+CSS布局问题,让两个DIV标签并排
- windows下安装Composer
- 关于typedef的讨论
- visual svn使用教程
- 模式开篇,策略模式,状态模式
- TTS-零基础入门-10分钟教你做一个语音功能
- JSSDK taobao js 研究 之 js sign的算法
- 第78讲:Type与Class实战详解
- Android应用:Button添加图片和文字
- IntelliJ IDEA 14.1上JFinal开发环境搭建手册
- double保留两位小数
- wait和waitpid详解
- UE4信息交互-蓝图类与关卡蓝图的信息交互