在原来的主要函数体外面套一个 while (!stack.isEmpty())
然后改写原来的return语句为push
并通过top来进行参数的递归改变(记得传完参要pop栈)
(需要特别注意退出递归的条件,并在进栈时加入判断条件)
/* 递归调用 */
quick_sort(a, l, i-1);
/* stack传参 */
st.push(l); st.push(i - 1);
- 实验内容
在 10.3 节中看到,递归通常使用栈来实现。在调用递归子程序的时候,参数、局
部变量和返回地址被压入栈中;而从子程序中返回的时候,这些值被弹出。一般地,可以通过令子程序本身维持一个栈来把递归程序转换成为非递归程序。使用这种方法来设计一个非递归函数 quicksort();使用栈来存放快速排序中子列表的第一个和最后一个位置。
- 实验运行结果
- 源代码
#include<iostream>
#include"stack"
using namespace std;
void quickSort(int* a, int l, int r) {
stack<int> st;
st.push(l);
st.push(r);
while (!st.empty()) {
int i, j, x;
int lt, rt;
rt=j = st.top();
st.pop();
lt=i = st.top();
st.pop();
x = a[i];
while (i < j)
{
while (i < j && a[j] > x)
j--; // 从右向左找第一个小于x的数
if (i < j)
a[i++] = a[j];
while (i < j && a[i] < x)
i++; // 从左向右找第一个大于x的数
if (i < j)
a[j--] = a[i];
}
a[i] = x;
if (lt < i - 1) {
st.push(lt);
st.push(i - 1);
}
if (i + 1 < rt) {
st.push(i + 1);
st.push(rt);
}
}
for (int i = 0; i<=r; i++)
cout << a[i] << " ";
return;
}
int main() {
int a[] = {33,5,843,24,1,313,5,0,22,21,-2};
quickSort(a, 0, 10);
}