快速排序
快速排序的基本思想是:
1.先从数列中取出一个数作为基准数。
2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
3.再对左右区间重复第二步,直到各区间只有一个数。
优化前的代码:
//简单选择排序
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 10
typedef struct
{
int r[MAXSIZE];
int length;
}SqList;
void swap(SqList * L,int i, int j)
{
int temp = L->r[i];
L->r[i] = L->r[j];
L->r[j] = temp;
}
int KeyPoint(SqList * L, int low, int high)
{
int KeyPoint;
int m = low + (high - low)/2;
KeyPoint = L->r[low];
while(low<high)
{
while(low<high && L->r[high]>=KeyPoint)
{
high--;
}
swap(L,low,high);
while(low<high && L->r[low]<=KeyPoint)
{
low++;
}
L->r[high] = L->r[low];
swap(L,low,high);
}
L->r[low] = L->r[0];
return low;
}
void Qsort( SqList * L, int low, int high )
{
int point;
if( low<high )
{
point = KeyPoint(L, low, high);
Qsort( L, low, point-1 );
Qsort( L, point+1, high );
}
}
void QuickSort(SqList * L)
{
Qsort( L, 1, L->length );
}
//测试
int main(void)
{
int i;
SqList * L = (SqList *)malloc(sizeof(SqList));
L->length = 8;
L->r[0] = 0;
L->r[1] = 5;
L->r[2] = 7;
L->r[3] = 8;
L->r[4] = 3;
L->r[5] = 4;
L->r[6] = 6;
L->r[7] = 1;
L->r[8] = 2;
QuickSort(L);
for( i = 1; i<=L->length; i++)
{
printf("%d\n",L->r[i]);
}
return 0;
}
因为每一次swap操作的效率还是比较低的,所以找一个“哨兵”用来做赋值操作。另外如果数组中的数字本来就是有序的,那快速排序的优势就没有了。
优化后的代码:
//简单选择排序
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define MAXSIZE 10
typedef struct
{
int r[MAXSIZE];
int length;
}SqList;
int KeyPoint(SqList * L, int low, int high)
{
int KeyPoint;
int m = low + (high - low)/2;
if(L->r[low]>L->r[high])
swap(L,low,high);
if(L->r[m]>L->r[high])
swap(L,high,m);
if(L->r[m]>L->r[low])
swap(L,m,low);
KeyPoint = L->r[low];
L->r[0] = KeyPoint;
while(low<high)
{
while(low<high && L->r[high]>=KeyPoint)
{
high--;
}
L->r[low] = L->r[high];
//swap(L,low,high);
while(low<high && L->r[low]<=KeyPoint)
{
low++;
}
L->r[high] = L->r[low];
//swap(L,low,high);
}
L->r[low] = L->r[0];
return low;
}
void Qsort( SqList * L, int low, int high )
{
int point;
if( low<high )
{
point = KeyPoint(L, low, high);
Qsort( L, low, point-1 );
Qsort( L, point+1, high );
}
}
void QuickSort(SqList * L)
{
Qsort( L, 1, L->length );
}
int main(void)
{
int i;
SqList * L = (SqList *)malloc(sizeof(SqList));
L->length = 8;
L->r[0] = 0;
L->r[1] = 5;
L->r[2] = 7;
L->r[3] = 8;
L->r[4] = 3;
L->r[5] = 4;
L->r[6] = 6;
L->r[7] = 1;
L->r[8] = 2;
QuickSort(L);
for( i = 1; i<=L->length; i++)
{
printf("%d\n",L->r[i]);
}
return 0;
}