用非递归的方法实现快速排序
2010-12-25 22:55
204 查看
貌似现在接触到的快速排序都使用递归方法,无可厚非在这个算法中递归确实是很不错的方法。但是纠结的算法老师要让我们实现非递归的方法来实现快速排序。上过数据结构的应该都知道递归的方法在程序执行的时候其实是通过栈来实现递归的现场保护(不知道是不是应该这么说)。所以还是使用了栈来实现这个算法,45 行代码应该很好理解。
#include <iostream> #include <stack> using namespace std; #define MAX_SIZE 8 int Qsort(int *a,int low,int high){ int key=a[low]; while(low<high){ while(low<high&&a[high]>=key) high--; a[low]=a[high]; while(low<high&&a[low]<=key) low++; a[high]=a[low]; } a[low]=key; return low; } int main(){ int a[MAX_SIZE]={49,38,65,97,76,13,27,49}; int low=0; int high=MAX_SIZE-1; int num=Qsort(a,low,high); stack<int> s; s.push(low); s.push(num-1); s.push(num+1); s.push(high); while(!s.empty()){ high=s.top(); s.pop(); low=s.top(); s.pop(); if(low<high){ num=Qsort(a,low,high); if(low<num-1){ s.push(low); s.push(num-1); } if(num+1<high){ s.push(num+1); s.push(high); } } } for(int i=0;i<MAX_SIZE;i++) cout<<a[i]<<" "; cout<<endl; return 0; }[/code]
相关文章推荐
- PHP递归实现快速排序的方法示例
- 【30】非递归方法实现快速排序
- c++实现二叉树的查找,插入,删除,深度,叶子节点数,度为1的节点数(递归方法)及运行实例结果
- Java 非递归 和非递归方法 实现两个有序单链表的合并
- 二叉数实现方法 非常绕的一个方法 递归
- 图的深度优先搜索(DFS)简介与实现(递归与非递归方法)
- Java中的递归详解及实现方法
- 第四十三题(递归和非递归俩种方法实现二叉树的前序遍历)
- 程序2.1:非递归方法实现迷宫
- 使用C语言递归与非递归实现字符串反转函数char *reverse(char *str)的方法
- 用递归的方法实现无限极分类
- 遍历河道递归方法 附项目实现
- 数据结构:题目(5)找两个字符串的最长公共子串(非递归实现方法)
- C--全排列的实现(递归方法) 傻子也能看懂的
- 求第n个斐波那契数(非递归与递归方法实现)
- 递归方法实现二分查找法
- php无限级分类实现代码(递归方法)
- PHP数组递归排序实现方法示例
- WinForm实现按名称递归查找控件的方法
- 输入一个整数,使用递归方法实现反向输出