递归比较简单 , 只对非递归实现下:
<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>
5514

被折叠的 条评论
为什么被折叠?



