1.排序思想
1.每次取待排序数组的第一个的数据(x),然后将当前的待排序的数组进行划分.划分成三部分. (小于x的数组)(x)(大于x的数组).
2.对 (小于x的数组)和 (小于x的数组)进行划分.就这样递归调用.
最关键的就是划分方法:
划分的思想:请查看图
3.使用递归调用划分方法即可.
2.算法执行结果
3.算法实现
3.1 数据结构
typedef int KeyType;
typedef struct {
KeyType key;
}RecType;
typedef RecType SeqSortList[MAXSIZE+1];//表中的0元素空着或用作哨兵单元
一般把数组中的第0个位置预留出来,就是为了作为哨兵,进行两个数据进行交换时,可以把哨兵作为临时变量进行交换.
3.2 单次划分方法
//快速排序中的--划分方法
int Partition(SeqSortList R,int i,int j){
//=========
printf("划分前:");
int low=i;//只为打印用
int height=j;只为打印用
logSort(R, low, height);
printf("\n");
//========
//对R[i]~R[j]区间内的记录进行一次划分排序
RecType x=R[i];//用区间第一个记录为基准
while(i<j){
//先从后面往前找第一个小于基准的值,赋给R[i]
while (i<j && R[j].key>=x.key) {
j--;
}
//找到了小于基准的值,赋给R[i]
if(i<j){
R[i]=R[j];
//这里i++,下面从从前面往后找第一个大于x的时候,从后一个开始查找
i++;
}
//然后从R[i]位置开始向后找,第一个大于x的值,赋给R[j].
while(i<j&& R[i].key<=x.key){
i++;
}
if(i<j){
R[j]=R[i];
j--;
}
}
R[i]=x;
//=========
printf("划分后:");
logSort(R, low, i-1);
logSort(R, i, i);
logSort(R, i+1, height);
printf("\n");
//========
return i;
}
3.3 快速排序方法
//快速排序方法
void QuickSort(SeqSortList R,int low,int hight){
int p;
if(low<hight){
p=Partition(R, low, hight);
QuickSort(R, low, p-1);
QuickSort(R, p+1, hight);
}
}
3.4 打印数组方法
//打印集合
void logSort(SeqSortList R,int start,int end);
打印数组集合: R:数组对象. start:开始打印的角标. end:结束打印的角标.
void logSort(SeqSortList R,int start,int end){
printf("[");
for(int i=start;i<=end;i++){
if(i==start){
printf("%d",R[i].key);
}else{
printf(",%d",R[i].key);
}
}
printf("]");
}
3.5 调用示例
void startQuick(){
int n=8;
SeqSortList R;
R[0].key=0;//哨兵
R[1].key=10;
R[2].key=15;
R[3].key=56;
R[4].key=6;
R[5].key=33;
R[6].key=5;
R[7].key=26;
R[8].key=8;
printf("无序R=");
logSort(R, 1, n);
printf("\n");
QuickSort(R,1,n);
printf("有序R=");
logSort(R, 1, n);
printf("\n");
}
4.复杂度
时间复杂度:O(n
log
2
n
\log_2{n}
log2n)
空间复杂度:O(
log
2
n
\log_2{n}
log2n)