一个快速排序算法代码分享

时间:2021-05-19

复制代码 代码如下:
/*
* 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;
}

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章