数据结构:非递归实现快排

文章介绍了如何使用栈数据结构来实现非递归的快速排序算法。首先定义了一个栈结构,包括初始化、销毁、入栈、出栈等操作。接着展示了非递归快排函数,通过栈来存储待排序区间的边界,不断进行分区并调整栈的状态,直到栈为空,完成排序。
摘要由CSDN通过智能技术生成

非递归实现快排需要借助栈数据结构实现,其中栈用来存储区间,以下为栈的实现

typedef int STDatatype;

typedef struct Stack
{
	int* a;
	int top;
	int capacity;
}ST;

void STInit(ST* ps)
{
	assert(ps);
	ps->a = (STDatatype*)malloc(sizeof(STDatatype) * 4);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		return;
	}
	ps->top = -1;
	ps->capacity = 4;
}

void STDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->top = -1;
	ps->capacity = 0;
}

void STPop(ST* ps)
{
	assert(ps);
	assert(ps->capacity != 0);
	(ps->top)--;
}

void STPush(ST* ps, STDatatype x)
{
	assert(ps);
	if (ps->top == ps->capacity - 1)
	{
		ps->a = (STDatatype*)realloc(ps->a,sizeof(STDatatype) * 2 * (ps->capacity));
		ps->capacity *= 2;
	}
	ps->top++;
	*(ps->a+ps->top) = x;
}

int STSize(ST* ps)
{
	assert(ps);
	return ((ps->top) + 1);
}

STDatatype STTop(ST* ps)
{
	assert(ps);
	assert(ps->top != -1);
	return (ps->a)[ps->top];
}

bool STEmpty(ST* ps)
{
	assert(ps);

	if (STSize(ps) == 0)
	{
		return true;
	}
	else
	{
		return false;
	}

}

 然后就可以实现非递归的快排了

void QuickSortNonR(int* a, int left, int right)
{
	ST s;
	STInit(&s);
	STPush(&s, right);
	STPush(&s, left);
	
	while (!STEmpty(&s))
	{
		int begin = STTop(&s);
		STPop(&s);
		int end = STTop(&s);
		STPop(&s);

		if (begin >= end)
		{
			continue;
		}

		int keyi = PartSort3(a, begin, end);
		STPush(&s, end);
		STPush(&s, keyi + 1);
		STPush(&s, keyi - 1);
		STPush(&s, begin);
	}

	STDestory(&s);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听说有人ID没取完就

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值