用递归的方法实现的算法一般都可以用非递归,即循环,的方法实现。实现的方法一般都需要借助一个栈。
记待排序数组为a, 有N个数。本算法的思路很简单:
1、先将数组的尾下标和首下标先后压入栈s;
2、当s不为空时,从s中先后弹出两个数front和end,表示待排序的区间。在该区间内使用partion算法,返回中位数下标mid;
3、当mid-front>=2时,a[front]~a[mid-1]需要进一步排序,将mid-1和front先后入栈;否则不做操作。当rear-mid>=2时,
a[mid+1]~a[rear]需要进一步排序,将rear和mid+1先后入栈;否则不做操作。
4、重复步骤2、3,直到s为空。
代码如下:
#include<iostream>
#include<stack>
using namespace std;
int Partition(int a[], int front, int rear);
int main()
{
int a[]={1, 3, -2, 42, 89, 26, 9, 0, 267};
int N=sizeof(a)/sizeof(a[0]);
stack<int> s;
s.push(N-1);
s.push(0);
int front, rear, mid;
while(!s.empty())
{
front=s.top();
s.pop();
rear=s.top();
s.pop();
mid=Partition(a, front, rear);
if(mid-front>=2)
{
s.push(mid-1);
s.push(front);
}
if(rear-mid>=2)
{
s.push(rear);
s.push(mid+1);
}
}
for(int i=0; i<N; i++)
cout<<a[i]<<' ';
cout<<endl;
system("pause");
}
int Partition(int a[], int front, int rear)
{
int temp=a[front];
int i=front, j=rear;
while(i<j)
{
while(a[j]>=temp && j>i)
j--;
if(j>i)
{
a[i]=a[j];
i++;
}
while(a[i]<=temp && j>i)
i++;
if(j>i)
{
a[j]=a[i];
j--;
}
}
a[i]=temp;
return i;
}