快速排序
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 10
typedef struct
{
int r[MAXSIZE];
int length;
}SqList;
int Partition(SqList *L,int low,int high);
void swap(SqList *L,int i,int j);
void QSort(SqList *L,int low,int high);
void QuickSort(SqList *L);
int main()
{
srand(time(NULL));
SqList *L=(SqList*)malloc(sizeof(SqList));
int i;
for(i=0;i<MAXSIZE;i++)
{
L->r[i]=rand()%15+1;
L->length++;
}
printf("排序前:\n");
for(i=0;i<MAXSIZE;i++)
{
printf("%d ",L->r[i]);
}
printf("\n");
QuickSort(L);
printf("排序后:\n");
for(i=0;i<MAXSIZE;i++)
{
printf("%d ",L->r[i]);
}
printf("\n");
return 0;
}
void swap(SqList *L,int i,int j)
{
int temp=L->r[i];
L->r[i]=L->r[j];
L->r[j]=temp;
}
void QuickSort(SqList *L)
{
QSort(L,0,L->length-1);
}
void QSort(SqList *L,int low,int high)
{
int pivot;
if(low<high)
{
pivot=Partition(L,low,high);/*将L->r[low..high]一分为二*/
/*算出枢轴值*/
QSort(L,low,pivot-1);/*对低子表进行排序*/
QSort(L,pivot+1,high);/*对高子表进行排序*/
}
else
return ;
}
int Partition(SqList *L,int low,int high)
{
int pivotkey;
pivotkey=L->r[low];/*用子表的第一个记录作为枢轴记录*/
while(low<high)/*从表的两端交替向中间扫描*/
{
while(low<high&&L->r[high]>=pivotkey)
{
high--;
}
swap(L,low,high);/*将表的右侧比枢轴小的记录交换到低端*/
while(low<high&&L->r[low]<=pivotkey)
{
low++;
}
swap(L,low,high);/*将表的左侧比枢轴大的记录交换到高端*/
}
return low;/*返回枢轴所在的位置*/
}
快速排序优化:
在排序元素小于7个的时候用插入排序比快速排序速度更快,此时线性表的大多数元素已经有序,所以插入排序比快速排序速度更快,另外将枢轴值送原来的最低端值变成原来在数组中间的值,节省了一部分开销
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSIZE 10
typedef struct
{
int r[MAXSIZE];
int length;
}SqList;
void QSort1(SqList *L,int low,int high);
int Partition1(SqList* L,int low,int high);
void swap(SqList *L,int i,int j);
void QuickSort1(SqList *L);
void InsertSort(SqList *L);
int main()
{
srand(time(NULL));
SqList *L=(SqList*)malloc(sizeof(SqList));
int i;
for(i=0;i<MAXSIZE;i++)
{
L->r[i]=rand()%15+1;
L->length++;
}
printf("排序前:\n");
for(i=0;i<MAXSIZE;i++)
{
printf("%d ",L->r[i]);
}
printf("\n");
QuickSort1(L);
printf("排序后:\n");
for(i=0;i<MAXSIZE;i++)
{
printf("%d ",L->r[i]);
}
printf("\n");
return 0;
}
void swap(SqList *L,int i,int j)
{
int temp=L->r[i];
L->r[i]=L->r[j];
L->r[j]=temp;
}
void QuickSort1(SqList *L)/*快速排序优化*/
{
QSort1(L,0,L->length-1);
}
int Partition1(SqList* L,int low,int high)/*快速排序优化*/
{
int pivotkey;
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);
}
pivotkey=L->r[low];
while(low<high)
{
while(low<high&&L->r[high]>=pivotkey)
{
high--;
}
L->r[low]=L->r[high];
while(low<high&&L->r[low]<=pivotkey)
{
low++;
}
L->r[high]=L->r[low];
}
L->r[low]=pivotkey;
return low;
}
void QSort1(SqList *L,int low,int high)/*快速排序优化*/
{
int pivot;
if((high-low)>7)//在数据元素小于7个的情况下插入排序更有优势
{
while(low<high)
{
pivot=Partition1(L,low,high);/*算出枢轴值*/
QSort1(L,low,pivot-1);/*对子表的递归排序*/
low=pivot+1;/*尾递归*/
}
}
else
{
InsertSort(L);
}
}