快速排序 非递归


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


<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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值