#include <iostream.h>
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define EQ(a,b) ((a) == (b))
#define LT(a,b) ((a) < (b))
#define LQ(a,b) ((a) <= (b))
#define MAXSIZE 20 // 一个用作示例的小顺序表的最大长度
typedef int KeyType; //定义关键字类型为整型
typedef struct { //记录类型
int key; //关键字项
int otherinfo; //其它数据项,具体类型在主程中定义
} RedType;
typedef struct { //顺序表类型
int r[MAXSIZE+1]; //r[0]闲置或用作哨兵单元
int length; //顺序表长度
} Sqlist;
//一分为二
int Partition(Sqlist &L,int low,int high)
{ // 交换顺序表L中子表L.r[low..high]的记录,使枢轴记录到位,
// 并返回其所在位置,此时在它之前(后)的记录均不大(小)于它
int pivotkey,t;
pivotkey=L.r[low]; //用子表的第一个记录作枢轴记录
while(low<high) { // 从表的两端交替地向中间扫描
while(low<high && L.r[high]>=pivotkey) --high;
t=L.r[low] ;L.r[low]=L.r[high]; L.r[high]=t; //将比枢轴记录小的记录交换到低端
while(low<high && L.r[low]<=pivotkey) ++low;
t=L.r[low] ;L.r[low]=L.r[high]; L.r[high]=t; //将比枢轴记录大的记录交换到高端
}
L.r[low]=L.r[0]; return low; //返回枢轴所在位置
}
//快速排序
void QSort(Sqlist &L,int low,int high)
{ //对顺序表L中的子序列L.r[low..high]作快速排序。
int pivotloc;
if(low<high) { //长度大于1
pivotloc=Partition(L, low, high); //将L.r[low..high]一分为二
QSort(L, low, pivotloc-1); //对低子表递归排序,pivotloc是枢轴位置
QSort(L, pivotloc+1, high); // 对高子表递归排序
}
}
//主程序
void main()
{
Sqlist L;
int i,low,high;
cout<<"输入顺序表的长度";
cin>>L.length;
for(i=1;i<=L.length;i++)
cin>>L.r[i];
low=1;
high=L.length;
QSort(L,low,high);
for(i=1;i<=L.length;i++)
{printf("%d",L.r[i]);printf(" ");}
printf("\n");
}
参考资料:ogin_u