直接插入排序+快速排序 c(实验课作业)

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef  struct  student
{
    char  name[8];
    int  score;
};

void insertsort(struct student stu[],int stunum)
{
    int i,j;
    for(i=2;i<=stunum;i++){
        if(stu[i].score<stu[i-1].score){
            stu[0]=stu[i];
            stu[i]=stu[i-1];
            for(j=i-2;stu[0].score<stu[j].score;j--){
                stu[j+1]=stu[j];
            }
            stu[j+1]=stu[0];
        }
    }
}

int quzhouindex(struct student stu[],int low,int high)
{
    stu[0]=stu[low];
    int quzhou_value=stu[0].score;
    while(low<high)
    {
        //第一次编译时,结果错误,无限循环,因为我的测试数据最后一个元素为49,和第一个元素相等
        //下面条件应为stu[high].score>q大于等于uzhou_value,而非大于 找比枢轴元素小的放在前面
        while(low<high && stu[high].score>=quzhou_value)high--;
        //刚从外层循环进入时,必定满足low<high。
        //但在经历high--后未必满足,到那时不仅会发生错误的比较,甚至可能出现下标越界
        stu[low]=stu[high];
        while(low<high && stu[low].score<=quzhou_value)low++;//找比枢轴元素大的放在后面
        stu[high]=stu[low];
    }
    stu[low]=stu[0];
    return low;
}
void quicksort(struct student stu[],int low,int high)
{
    //表长大于1,表长小于等于1的表无需排序
    int index;
    if(low<high){
        index=quzhouindex(stu,low,high);
        quicksort(stu,low,index-1);
        quicksort(stu,index+1,high);
    }
}

void printstu(struct student stu[],int stunum)
{
    int j=1;
    for(int i=stunum; i>0; i--)
    {

        if(i!=stunum && stu[i].score!=stu[i+1].score)
        {
            j++;
        }
        printf("%2d  %4d  %8s\n",j,stu[i].score,stu[i].name);

    }
}
int main()
{
    int stunum;
    struct student stu[MAXSIZE];

    printf("请输入学生人数:\n");
    scanf("%d",&stunum);
    for(int i=1; i<=stunum; i++)
    {
        scanf("%d %s",&stu[i].score,&stu[i].name);
    }

    //直接插入排序
    //insertsort(stu,stunum);
    printstu(stu,stunum);


    //快速排序
    quicksort(stu,1,stunum);
    printstu(stu,stunum);
    return 0;
}
/*
测试数据:
8
49 Abc
38 Bbc
65 Cbc
97 Dbc
76 Ebc
13 Fbc
27 Gbc
49 Hbc
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值