快速排序算法:
思想:
附设两个指针low和high,他们的储值分别为low和high,设枢轴记录的关键字pivotkey,则首先从high所指位置起向前搜索找到第一个关键字小于pivotkey的记录和枢轴记录互相交换,然后从low所指位置向后检索,找到第一个关键字大于pivotkey的记录和枢轴记录互相交换,重复这两步直至low=high为止。
优化:
先将枢轴记录暂存在r[0]的位置上,排序过程中只做r[low]或r[high]的单向移动,直至一趟排序结束后再将枢轴记录移至正确位置上。
算法:
#include<stdio.h>
#define MAXSIZE 20 //数组大小
typedef int KeyType; //关键字类型
typedef int InfoType; //元素信息类型
//数组中元素的信息
typedef struct{
KeyType key; //元素排序的关键字
InfoType otherinfo; //元素信息
}RedType;
//数组的类型
typedef struct{
RedType r[MAXSIZE+1];
int length;
}SqList;
//初始化待排序列
void Init(SqList *L,int a[],int length)
{
int i;
RedType rt;
for(i = 0;i < length;i++){
rt.key = a[i];
rt.otherinfo = i;
L->r[i] = rt;
}
L->length = length;
}
//划分数组
int Partition(SqList *L,int low,int high){
int pivotkey;
L->r[0] = L->r[low];
pivotkey = L->r[low].key;
while(low<high){
//从数组最后一个元素开始查找小于pivotkey的元素
while(low<high && L->r[high].key >= pivotkey) --high;
L->r[low] = L->r[high];
//从前往后找大于pivotkey的元素
while(low<high && L->r[low].key <= pivotkey) ++low;
L->r[high] = L->r[low];
}
L->r[low] = L->r[0];
return low;
}
//快速排序主程序
void QSort(SqList *L,int low,int high){
int pivotloc;
if(low<high){
pivotloc = Partition(L,low,high); //划分数组
QSort(L,low,pivotloc-1); //递归划分数组左部分
QSort(L,pivotloc+1,high); //递归划分数组右部分
}
}
int main(){
SqList L;
int i;
int a[9] = {0,49,38,65,97,76,13,27,49};
Init(&L,a,9);
printf("排序前:");
for(i = 0;i < 9;i++){
printf("%-2d ",L.r[i].key);
}
printf("\n下标号:");
for(i = 0;i < 9;i++){
printf("%-2d ",L.r[i].otherinfo);
}
//数组a[0]是岗哨 待排序列是1~8的元素
QSort(&L,1,8);
printf("\n\n排序后:");
for(i = 0;i < 9;i++){
printf("%-2d ",L.r[i].key);
}
printf("\n下标号:");
for(i = 0;i < 9;i++){
printf("%-2d ",L.r[i].otherinfo);
}
printf("\n\n");
return 0;
}
运行结果 :