快速排序 非递归

来源:互联网 发布:ppt数据分析图制作教程 编辑:程序博客网 时间:2024/05/16 12:46


递归比较简单 , 只对非递归实现下:


<span style="font-size:16px;">#include <stdio.h>/*** 基本思想和递归一样,partion()函数也可以作为递归方法的划分。* 将基准点左右两个子问题 看成一个段***/typedef struct{int low;int high;}Segment;  // 每一段 表示一个子问题Segment stack[100]; //模拟栈 //寻找划分点, 每一次调用都确定一个位置int partion(int a[],int low,int high){int pivot = a[low];  //以第一个元素为基点while (high > low){while(high > low&&a[high] >= pivot) high--;a[low] = a[high];// 比基点小的元素左移while (high > low&&a[low] <= pivot) low++;a[high] = a[low];//比基点大的元素右移}a[low] = pivot; //基点元素放在最终位置return low;}void sort(int a[],int low,int high){int top = -1; //初始化栈,-1表示栈空Segment seg = {low, high};stack[++top] = seg; //将原始序列看成一个段,放入栈中while (top != -1){seg = stack[top--]; //出栈int position = partion(a, seg.low, seg.high);//左子问题存在 则入栈 if (position-1 > seg.low){Segment left = {seg.low,position-1};stack[++top] = left;}//右子问题存在 则入栈if (position + 1 < high){Segment right = {position+1,seg.high};stack[++top] = right;}}}int main(){int a[8] = {1, 9, 4, 2, 8, 6, 3, 5};int n = 8;sort(a, 0, n - 1);for (int i = 0; i < n; i++){printf("%d ",a[i]);}printf("\n");return 0;}</span>


0 0