复制代码 代码如下:
/*
* quickSort.c
*
* Created on: 2012-4-9
* Author: LW
*/
#include <stdio.h>
#include <string.h>
typedef struct _student
{
int id;
char name[30];
}student,*pStudent;
student students[20] =
{
{13,"狐狸金"},{15,"杜十娘"},{8,"葫芦娃"},{4,"喜羊羊"},
{14,"叮当猫"},{18,"孙悟空"},{3,"格列佛"},{6,"咖啡猫"},
{19,"猪八戒"},{11,"程序员"},{5,"鲁滨逊"},{9,"金枪鱼"},
{10,"马大哈"},{12,"周星星"},{1,"灰太狼"},{2,"唐老鸭"},
{20,"子虚君"},{16,"乌有君"},{7,"小二郎"},{17,"贾宝玉"},
};
//students[]是需要进行排序的数组,length是students数组的元素个数
void quickSort(student students[],int length)
{
int i,j,flag = students[0].id;
student stutemp;
int t;
if(length>1)
{
for(t=0;t<length;t++)
{
printf("%d ",students[t].id);
}
printf("\n");
//为分区选好分裂点
for(i=0,j=length-1;i<j;)
{
for(;students[i].id<flag;i++);
for(;students[j].id>flag;j--);
stutemp.id = students[j].id;
strcpy(stutemp.name,students[j].name);
students[j].id = students[i].id;
strcpy(students[j].name,students[i].name);
students[i].id = stutemp.id;
strcpy(students[i].name,stutemp.name);
}
//打印排序过程
for(t=0;t<length;t++)
{
printf("%d ",students[t].id);
}
printf("----排序后\n-----------------------------------中轴:%d 中轴下标:%d\n",flag,j);
//进行分区并对分区进行递归调用quickSort,在原数组空间里进行操作
quickSort(&students[0],j+1);
quickSort(&students[j+1],length-j-1);
}
}
int main()
{
int i;
//排序前打印
printf("排序前:\n");
for(i=0;i<20;i++)
{
printf("%d %s\t",students[i].id,students[i].name);
if(!((i+1)%5))
{
printf("\n");
}
}
quickSort(students,20);
//排序后打印
printf("__________________________________________________________________\n排序后:\n");
for(i=0;i<20;i++)
{
printf("%d %s\t",students[i].id,students[i].name);
if(!((i+1)%5))
{
printf("\n");
}
}
return 0;
}