20220531模拟实现qsort函数

int cmp_int(const void* e1, const void* e2)
{
    return *(int*)e1 - *(int*)e2;
}

void print(int arr[], int sz)
{
    int i = 0;
    for (i = 0; i < sz; i++)
    {
        printf("%d ", arr[i]);
    }
}

void test1()
{
    int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
    int sz = sizeof(arr) / sizeof(arr[0]);
    qsort(arr, sz, sizeof(arr[0]), cmp_int);
    print(arr, sz);
}

struct Stu
{
    char name[20];
    int age;
};

int sort_by_age(const void* e1, const void* e2)
{
    return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;//要改变排序方式可以改变两个值的位置
}

int sort_by_name(const void* e1, const void* e2)
{
    return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e1)->name);
}

void test2()
{
    struct Stu s[] = { {"zhangsan", 30},{"lisi",34},{"wangwu",20} };
    //按照年龄来排序
    int sz = sizeof(s) / sizeof(s[0]);
    /*qsort(s, sz, sizeof(s[0]), sort_by_age);*/
    //按照名字排序
    qsort(s, sz, sizeof(s[0]), sort_by_name);
}

void swap(char* buf1, char* buf2, int width)
{
    int i = 0;
    for (i = 0; i < width; i++)
    {
        char tmp = *buf1;
        *buf1 = *buf2;
        *buf2 = tmp;
        buf1++, buf2++;
    }
}

//模仿qsort实现一个冒泡排序的通用算法
void banbble_sort(void* base, int sz, int width, int (*tmp)(const void* e1, const void* e2))
{
    int i = 0;
    for (i = 0; i < sz - 1; i++)
    {
        int j = 0;
        for (j = 0; j < sz - 1 - i; j++)
        {
            //两个元素比较
            if (tmp((char*)base + j * width,(char*)base + (j + 1) * width) > 0)
            {
                //交换
                swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
            }
        }

    }
}

void test3()
{
    int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
    int sz = sizeof(arr) / sizeof(arr[0]);
    banbble_sort(arr, sz, sizeof(arr[0]), cmp_int);
    print(arr, sz);
}

void test4()
{
    struct Stu s[] = { {"zhangsan", 30},{"lisi",34},{"wangwu",20} };
    //按照年龄来排序
    int sz = sizeof(s) / sizeof(s[0]);
    /*qsort(s, sz, sizeof(s[0]), sort_by_age);*/
    //按照名字排序
    banbble_sort(s, sz, sizeof(s[0]), cmp_int);
}

int main()
{
    /*test1();*/
    /*test2();*/
    /*test3();*/
    test4();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值