(1)一趟排序之后,若子序列已有序(无交换),则不参加排序,否则先对长度较短的子序列进行排序,且将另一子序列的上、下界入栈保存;
(2)若待排记录数≤3,则不再进行分割,而是直接进行比较排序。
#include<stdio.h>
#include<stdlib.h>
#include"stack-10.30.cpp"
#define maxsize 100
typedef struct{
int r[maxsize];
int length;
}SqList;
int QuickSort(SqList &L,int low,int high){
int i,j,temp;
i=low,j=high;
if(i<j){
L.r[0]=L.r[i];
while(i<j){
while(i<j&&L.r[j]>L.r[0]) j--;
if(i<j){
L.r[i]=L.r[j];
i++;
}
while(i<j&&L.r[i]<L.r[0]) i++;
if(i<j){
L.r[j]=L.r[i];
j--;
}
}
L.r[i]=L.r[0];
// QuickSort(L,low,i-1);
// QuickSort(L,i+1,high);
return i;
}
}
void insertSort(SqList &L,int low,int high){ //插入排序
int i,j,temp;
for(i=low+1;i<=high;i++){
temp=L.r[i];
j=i-1;
while(j>low&&temp<L.r[j]){
L.r[j+1]=L.r[j];
--j;
}
L.r[j+1]=temp;
}
}
void sort(SqList &L){
SqStack S=InitStack(50);
Push(S,1);
Push(S,L.length-1);
int low,high,pivot,len1,len2;
while(S.base!=S.top){
high=Pop(S);
low=Pop(S);
if(high-low+1<3){
insertSort(L,low,high);
}else{
pivot=QuickSort(L,low,high);
len1=pivot-low;
len2=high-pivot;
if(len1>len2){
Push(S,low);
Push(S,pivot-1);
Push(S,pivot+1);
Push(S,high);
}else{
Push(S,pivot+1);
Push(S,high);
Push(S,low);
Push(S,pivot-1);
}
}
}
}
int main(){
SqList L;
int i;
scanf("%d",&L.length);
for(i=1;i<L.length;i++){
scanf("%d",&L.r[i]);
}
sort(L);
for(i=1;i<L.length;i++){
printf("%d ",L.r[i]);
}
return 0;
}
stack-10.30.cpp
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
SqStack InitStack(int size){
SqStack S;
S.base=(ElemType*)malloc(size*sizeof(ElemType));
if(!S.base) exit(0);
S.top=S.base;
S.stacksize=size;
return S;
}
void Push(SqStack &S,ElemType x){
if(S.top-S.base>=S.stacksize) exit(0);
*S.top=x;
S.top++;
}
ElemType Pop(SqStack &S){
if(S.base==S.top) exit(0);
S.top--;
ElemType x=*S.top;
return x;
}
输入:
9
49 38 65 97 76 13 27 99
输出:
13 27 38 49 65 76 97 99