随笔-15  评论-10  文章-1  trackbacks-0
在前2个Posts中,使用了递归的方式实现快速排序算法,如果想
去掉递归,则我们需要使用栈数据结构,

//为数组分区,返回新的支点位置(前2个Posts中已经实现)
int partition(int array[], int left, int right);

//记录数组信息的结构
typedef struct _qsort_range {
        int left, right;
}qsort_range;

//记录数组信息的栈
typedef stack<qsort_range, list<qsort_range> > range_stack;

//用非递归方法实现快速排序
void qsort2(int array[], int left, int right)
{
        /*数组分区*/
        int pos = partition(array, left, right);
        if (pos == -1) return;

        range_stack s;
        if (pos >= left) {
                /*左子数组left、right信息保存,注意:先左再右*/
                if (pos + 1 < right) {
                        qsort_range r2;
                        r2.left = pos+1; r2.right = right;
                        s.push(r2);
                }
                /*右子数组left、right信息保存*/
                if (pos - 1 > left) {
                        qsort_range r1;
                        r1.left = left; r1.right=pos-1;
                        s.push(r1);
                }
        }

        /*模拟递归调用*/
        while (s.size() > 0) {
                /*出栈*/
                qsort_range r3 = s.top();
                s.pop();

                /*数组分区*/
                int pos3 = partition(array, r3.left, r3.right);
                if (pos3 != -1) {
                        /*子数组的left、right信息保存*/
                        if (pos3 >= r3.left) {
                                if (pos3 + 1 < r3.right) {
                                        qsort_range r31;
                                        r31.left = pos3+1; r31.right = r3.right;
                                        s.push(r31);
                                }
                                if (pos3 - 1 > r3.left) {
                                        qsort_range r32;
                                        r32.left = r3.left; r32.right=pos3-1;
                                        s.push(r32);
                                }
                        }
                }
        }
}
posted on 2006-09-12 21:50 hzb 阅读(2432) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理