非递归实现快排需要借助栈数据结构实现,其中栈用来存储区间,以下为栈的实现
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);
}