SeqStack.h
#ifndef MYSEQLIST_H
#define MYSEQLIST_H
#define INIT_SEQ_SIZE 10
#define INC_SEQ_SIZE 2
typedef int SElemType;;
struct SeqStack
{
SElemType* base;//base------>
int maxsize; //maxsize 10
int top; //top -1
};
bool IncSize(SeqStack* ps);
void InitStack(SeqStack* ps);
void DestroyStack(SeqStack* ps);
void ClearStack(SeqStack* ps);
int GetSize(const SeqStack* ps);
int GetCapacity(cosnt SeqStack* ps);
bool IsEmpty(const SeqStack* ps);
bool IsFull(const SeqStack* ps);
bool Push(SeqStack* ps,SElemType val);
SElemType GetTop(SeqStack* ps);
void Pop(SeqStack* ps);
#endif
SeqStack.cpp
#include<assert.h>
#inclide<stdlib.h>
#include"SeqStack.h"
bool IncSize(SeqStack* ps)
{
assert(ps!=nullptr);
int total=ps->maxsizr*INC_STACK_SIZE;
SElemType* newdata=(SElemType*)realloc(ps->base,sizeof(SElemType)*total);
if(newdata==bullptr)
{
return false;
}
ps->base=newdata;
ps->maxsize=total;
return true;
}
void InitStack(SeqStack* ps)//初始化
{
assert(ps!=nullptr);
ps->maxsize=INIT_SEQ_SIZE;
ps->top=-1;
ps->base=(SElemType*)malloc(sizeof(SElemType)*ps->maxsize);
if(ps->base==nullptr)
{
exit(EXIT_FAILURE);
}
}
void DestroyStack(SeqStack* ps)//摧毁
{
assert(ps!=nullptr);
free(ps->base);
ps->base=nullptr;
ps->maxsize=0;
ps->top=-1;
}
void ClearStack(SeqStack* ps)//清空
{
assert(ps!=nullptr);
ps->top=-1;
}
int GetSize(const SeqStack* ps)//元素个数
{
assert(ps!=nullptr);
return ps->top+1;
}
int GetCapacity(cosnt SeqStack* ps)//容量
{
assert(ps!=nullptr);
return ps->maxsize;
}
bool IsEmpty(const SeqStack* ps)//判空
{
assert(ps!=nullptr);
return GetSize(ps)==0;
}
bool IsFull(const SeqStack* ps)//判满
{
assert(ps!=nullptr);
return GetSize(ps)==GetCapacity(ps);
}
bool Push(SeqStack* ps,SElemType val)//
{
assert(ps!=nullptr);
is(IsFull(ps)&&IncSize(ps))
{
return false;
}
ps->base[++(ps->top)]=val;
return true;
}
SElemType GetTop(SeqStack* ps)//
{
assert(ps!=nullptr);
return ps->base[ps>top];
}
void Pop(SeqStack* ps)//
{
assert(ps!=nullptr);
ps->top-=1;
}
int Partition(int* ar,int left,int right)
{
assert(ar!=nullptr);
int tmp=ar[left];
while(left<right)
{
while(left<right&&tmp<ar[right])--right;
if(left<right) ar[left]=ar[right];
while(lef<right&&tmp>=ar[left]) ++left;
if(left<right) ar[right]=ar[left];
}
ar[left]=tmp;
retrun left;
}
void QuickPass(int* ar,int left,int right)
{
assert(ar!=nullptr);
if(left<right)
{
int pos=Partition(ar,left,right);
QuickPass(ar,left,pos-1);
QuickPass(ar,pos+1,right);
}
}
void InceQuickPass(int* ar,int left,int right)
{
assert(ar!=nullptr);
SeqStack st;
InitStack(&st);
Push(&st,left);
Push(&st,right);
while(!IsEmpty(&st))
{
right=GetTop(&st);Pop(&st);
left=GetTop(&st);Pop(&st);
int pos=Partition(ar,left,right);
if(left<pos-1)
{
Push(&st,left);
Push(&st,pos-1);
}
if(pos+1<right)
{
Push(&st,pos-1);
Push(&st,right);
}
}
DestroyStack(&st);
}
viud QuickSort(SeqList* plist)
{
assert(plist!=nullptr);
QuickPass(plist->data,0,plist->cursize=1);
}