- #include<iostream>
- #define INITSIZE 20
- #define INCREAMENT 5
- #define OK 1
- #define ERROR 0
- #define OVERFLOW -1
- using namespace std;
- typedef struct Lnode
- {
- int key;
- char info;
- }LNode;
- typedef struct
- {
- LNode *r;
- int length;
- int listsize;
- }SqList;
- int initList(SqList &L)
- {
- L.r=(LNode *)malloc(sizeof(LNode) * INITSIZE);
- if(!L.r) exit(OVERFLOW);
- L.length=1;
- L.r[0].key = 0;
- L.listsize=INITSIZE;
- return OK;
- }
- int Listinsert(SqList &L,int i,LNode *elem)
- {
- if(i<1||i>L.length+1) return ERROR;
- if(L.length>=L.listsize)
- {
- LNode *newbase=(LNode *)realloc(L.r,(L.length+INCREAMENT)*sizeof(LNode));
- if(!newbase) exit(OVERFLOW);
- L.r=newbase;
- L.listsize+=INCREAMENT;
- }
- // L.r[i].key = elem->key;
- LNode *q=&L.r[i];
- for(LNode *p=&(L.r[L.length-1]);p>=q;--p)
- {
- *(p+1)=*p;
- }
- L.r[i].key=elem->key;
- ++L.length;
- return OK;
- }
- int Partition(SqList &L,int low,int high)
- {
- L.r[0].key=L.r[low].key;
- int pivotkey=L.r[low].key;
- while(high>low)
- {
- while(low<high && L.r[high].key>=pivotkey) --high;
- if(low<high) L.r[low].key=L.r[high].key;
- while(low<high && L.r[low].key<=pivotkey) ++low;
- if(low<high) L.r[high].key=L.r[low].key;
- }
- L.r[low].key=pivotkey;
- return high;
- }
- int Qsort(SqList &L,int low,int high)
- {
- if(low<high)
- {
- int pivotkey;
- pivotkey=Partition(L,low,high); cout<<"pivotkey "<<pivotkey<<" low "<<low<<" high "<<high<< endl;
- for(int i=1;i<L.length;++i)
- cout<<L.r[i].key<<" ";
- cout<<endl;
- Qsort(L,low,pivotkey-1);
- Qsort(L,pivotkey+1,high);
- }
- return OK;
- }
- int Quicksort(SqList &L)
- {
- Qsort(L,1,L.length - 1);
- return OK;
- }
- int main(void)
- {
- SqList L;
- initList(L);
- int i,num;
- cout<<"請輸入排序的個數"<<endl;
- cin>>num;
- for(i=1;i<=num;i++)
- {
- LNode *p=(LNode *)malloc(sizeof(LNode));
- cout<<"輸入關鍵字\n";
- cin>>p->key;
- // cout<<"輸入信息"<<endl;
- // cin>>p->info;
- Listinsert(L,i,p);
- }
- cout<<"排序前:\n";
- for(i=1;i<L.length;++i)
- cout<<L.r[i].key<<" ";
- // cout<<"TEST HERE"<<endl;
- cout<<endl;
- // cout<<L.length<<endl;
- Quicksort(L);
- cout<<"排序後:"<<endl;
- for(i=1;i<L.length;++i)
- cout<<L.r[i].key<<" ";
- return OK;
- }