45.使用qsort对结构体数组进行排序,实现对结构的体一级排序和二级排序,进一步了解qsort的原理

qsort对结构体数组进行排序时,可以根据结构体元素中的任意某个成员进行比较之后,如果要交换则会连带结构体中其他成员的一起进行整体的结构体元素交换
所以感觉真是万能排序接口



只进行对结构体的一级排序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _stu
{
    char name[10];
    float score;
}Stu;


int callBackCompare(const void * pa, const void * pb)//一级升序
{
#if 0//正确
    if(strcmp((*(Stu*)pa).name,(*(Stu*)pb).name)>0)
        return 1;
    else
        return 0;//或return -1;都行,毕竟qsort只对正数感兴趣
#endif

#if 1  //正确
    if(strcmp(((Stu*)pa)->name,((Stu*)pb)->name) > 0 )
        return 1;
    else
        return 0;//或return -1;都行,毕竟qsort只对正数感兴趣

#endif
}

int main(void)
{
    Stu stu[] = {{"aaa",23.5},
                 {"xxx",45.6},
                 {"bbb",89},
                 {"xxx",23.4},
                 {"yyy",100}};

    qsort(stu,sizeof(stu)/sizeof(*stu),sizeof(Stu),callBackCompare);

    int i;
    for(i = 0;i<5;i++)
    {
        printf("%s,%f\n",stu[i].name,stu[i].score);

    }

    return 0;
}




对结构体一级排序的同时进行二级排序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _stu
{
    char name[10];
    float score;
}Stu;


int callBackCompare(const void * pa, const void * pb)//一级升序二级降序
{
#if 0//正确
    if(strcmp((*(Stu*)pa).name,(*(Stu*)pb).name)>0)//对1级进行升序
        return 1;
    else
    {
        if( (*(Stu*)pa).score < (*(Stu*)pb).score )//对2级进行降序
        {
            return 1;
        }
        else
            return 0;
    }
#endif

#if 0  //正确
    if(strcmp(((Stu*)pa)->name,((Stu*)pb)->name) > 0 )
        return 1;
    else
    {
        if( ((Stu*)pa)->score < ((Stu*)pb)->score )//对2级进行降序
        {
            return 1;
        }
        else
            return 0;
    }

#endif
}

int main(void)
{
    Stu stu[] = {{"aaa",23.5},
                 {"xxx",45.6},
                 {"bbb",89},
                 {"xxx",23.4},
                 {"yyy",100}};

    qsort(stu,sizeof(stu)/sizeof(*stu),sizeof(Stu),callBackCompare);

    int i;
    for(i = 0;i<5;i++)
    {
        printf("%s,%f\n",stu[i].name,stu[i].score);

    }

    return 0;
}

 

posted @ 2018-08-22 12:48  2018年8月10日注册  阅读(2907)  评论(0编辑  收藏  举报