新浪面试题 快速排序非递归实现
2015-09-21 16:03
274 查看
int Partition(int *a,int low,int high)
{
while(low<high)
{
while(low<high && a[high] >= a[low])
--high;
swap(a[low],a[high]);
while(low<high && a[low] <= a[high])
++low;
swap(a[low],a[high]);
}
return low;
}
void quickSort(int *a,int low ,int high) {
if(a== NULL || low< 0 || high <0)
return ;
stack<int> s;
if(low<high)
{
int pivot = Partition(a,low,high);
if(low < pivot -1)
{
s.push(low);
s.push(pivot-1);
}
if(pivot+1 < high)
{
s.push(pivot+1);
s.push(high);
}
while(!s.empty())
{
int start = s.top();
s.pop();
int end = s.top();
s.pop();
pivot = Partition(a,start,end);
if(start < pivot -1 )
{
s.push(start);
s.push(pivot-1);
}
if(pivot+1 < end)
{
s.push(pivot+1);
s.push(end);
}
}
}
}
{
while(low<high)
{
while(low<high && a[high] >= a[low])
--high;
swap(a[low],a[high]);
while(low<high && a[low] <= a[high])
++low;
swap(a[low],a[high]);
}
return low;
}
void quickSort(int *a,int low ,int high) {
if(a== NULL || low< 0 || high <0)
return ;
stack<int> s;
if(low<high)
{
int pivot = Partition(a,low,high);
if(low < pivot -1)
{
s.push(low);
s.push(pivot-1);
}
if(pivot+1 < high)
{
s.push(pivot+1);
s.push(high);
}
while(!s.empty())
{
int start = s.top();
s.pop();
int end = s.top();
s.pop();
pivot = Partition(a,start,end);
if(start < pivot -1 )
{
s.push(start);
s.push(pivot-1);
}
if(pivot+1 < end)
{
s.push(pivot+1);
s.push(end);
}
}
}
}
相关文章推荐
- 记录 android 开发的一个 "面试" 问题
- 低效程序员的7个坏习惯
- 职场准备(一)
- 新手程序员应该知道的7件事-兄弟连IT教育
- Sring面试题
- 黑马程序员——Java基础语法(三)---数组
- 微软面试题
- 编程面试的10大算法概念汇总
- 程序猿的学习就是那么回事
- 黑马程序员——面向对象最全总结:谁说程序员没有“对象”
- 总结面试题
- 求职技能储备--软件工程师
- 黑马程序员——面向对象
- 黑马程序员——异常
- 黑马程序员--文件类型
- 程序员教你如何追女生
- 黑马程序员-关于配置环境变量
- Java程序员从笨鸟到菜鸟之(五十三)细谈Hibernate(四)Hibernate常用配置文件详解
- 2015程序员值得收藏的十大主流button模式
- 【Java基金会】Java整理面试问题和评论(一)